这里提出的想法非常好,但也有一些缺点:
inspect.getouterframes
并且args[0].__class__.__name__
不适合普通函数和静态方法。
__get__
必须在一个被拒绝的类中@wraps
。
@wraps
本身应该更好地隐藏痕迹。
所以,我结合了这个页面的一些想法,链接,文档和我自己的头脑,
终于找到了一个解决方案,它缺乏上述所有三个缺点。
结果,method_decorator
:
- 知道装饰方法绑定到的类。
- 通过更正确地回答系统属性来隐藏装饰器跟踪
functools.wraps()
。
- 包含用于绑定未绑定实例方法、类方法、静态方法和普通函数的单元测试。
用法:
pip install method_decorator
from method_decorator import method_decorator
class my_decorator(method_decorator):
# ...
有关使用详情,请参阅完整的单元测试。
这里只是method_decorator
类的代码:
class method_decorator(object):
def __init__(self, func, obj=None, cls=None, method_type='function'):
# These defaults are OK for plain functions
# and will be changed by __get__() for methods once a method is dot-referenced.
self.func, self.obj, self.cls, self.method_type = func, obj, cls, method_type
def __get__(self, obj=None, cls=None):
# It is executed when decorated func is referenced as a method: cls.func or obj.func.
if self.obj == obj and self.cls == cls:
return self # Use the same instance that is already processed by previous call to this __get__().
method_type = (
'staticmethod' if isinstance(self.func, staticmethod) else
'classmethod' if isinstance(self.func, classmethod) else
'instancemethod'
# No branch for plain function - correct method_type for it is already set in __init__() defaults.
)
return object.__getattribute__(self, '__class__')( # Use specialized method_decorator (or descendant) instance, don't change current instance attributes - it leads to conflicts.
self.func.__get__(obj, cls), obj, cls, method_type) # Use bound or unbound method with this underlying func.
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __getattribute__(self, attr_name): # Hiding traces of decoration.
if attr_name in ('__init__', '__get__', '__call__', '__getattribute__', 'func', 'obj', 'cls', 'method_type'): # Our known names. '__class__' is not included because is used only with explicit object.__getattribute__().
return object.__getattribute__(self, attr_name) # Stopping recursion.
# All other attr_names, including auto-defined by system in self, are searched in decorated self.func, e.g.: __module__, __class__, __name__, __doc__, im_*, func_*, etc.
return getattr(self.func, attr_name) # Raises correct AttributeError if name is not found in decorated self.func.
def __repr__(self): # Special case: __repr__ ignores __getattribute__.
return self.func.__repr__()