编程语言
首页 > 编程语言> > 装饰上下文管理器中的任何python函数

装饰上下文管理器中的任何python函数

作者:互联网

我想创建一个python上下文管理器,它将允许以下操作(用reverse_decorator应用修饰的函数,如果它是字符串,则将第一个参数取反):

print('hi')
with MyFunctionDecorator('print', reverse_decorator):
    print('hello')
print('bye')

以导致:

hi
olleh
bye

关键不是打印功能本身,而是编写这种上下文管理器,它可以修饰任何功能-本地,全局,内置,任何模块.在python中甚至可能吗?我该怎么办?

编辑:为了澄清一点,重点是不必更改with上下文中的代码.

解决方法:

这是我的方法:

from contextlib import contextmanager
from importlib import import_module

@contextmanager
def MyFunctionDecorator(func, decorator):
    if hasattr(func, '__self__'):
        owner = func.__self__
    elif hasattr(func, '__objclass__'):
        owner = func.__objclass__
    else:
        owner = import_module(func.__module__)
        qname = func.__qualname__
        while '.' in qname:
            parent, qname = qname.split('.', 1)
            owner = getattr(owner, parent)
    setattr(owner, func.__name__, decorator(func))
    yield
    setattr(owner, func.__name__, func)

# Example decorator, reverse all str arguments
def reverse_decorator(f):
    def wrapper(*args, **kwargs):
        newargs = []
        for arg in args:
            newargs.append(arg[::-1] if isinstance(arg, str) else arg)
        newkwargs = {}
        for karg, varg in kwargs.values():
            newkwargs[karg] = varg[::-1] if isinstance(varg, str) else varg
        return f(*newargs, **newkwargs)
    return wrapper

# Free functions
print('hi')
with MyFunctionDecorator(print, reverse_decorator):
    print('hello')
print('bye')

# Class for testing methods (does not work with builtins)
class MyClass(object):
    def __init__(self, objId):
        self.objId = objId
    def print(self, arg):
        print('Printing from object', self.objId, arg)

# Class level (only affects instances created within managed context)
# Note for decorator: first argument of decorated function is self here
with MyFunctionDecorator(MyClass.print, reverse_decorator):
    myObj = MyClass(1)
    myObj.print('hello')

# Instance level (only affects one instance)
myObj = MyClass(2)
myObj.print('hi')
with MyFunctionDecorator(myObj.print, reverse_decorator):
    myObj.print('hello')
myObj.print('bye')

输出:

hi
olleh
bye
Printing from object 1 olleh
Printing from object 2 hi
Printing from object 2 olleh
Printing from object 2 bye

这应该在功能和其他模块之间起作用,以此类推,因为它修改了模块或类的属性.类方法很复杂,因为一旦创建了类的实例,它的属性就指向创建对象时类中定义的函数,因此您必须在修改特定实例的行为或修改对象的行为之间进行选择.如示例所示,在托管上下文中创建新实例.同样,尝试装饰诸如list或dict这样的内置类的方法也不起作用.

标签:python-decorators,python
来源: https://codeday.me/bug/20191109/2012634.html