大家都知道装饰器是一个很著名的设计模式,经常被用于AOP(面向切面编程)的场景,较为经典的有插入日志,性能测试,事务处理,Web权限校验, Cache等。
Python语言本身提供了装饰器语法(@),典型的装饰器实现如下:
- @function_wrapper
- def function():
- pass
- def function():
- pass
- function = function_wrapper(function)
装饰器的两种实现
函数包装器 - 经典实现
- def function_wrapper(wrapped):
- def _wrapper(*args, **kwargs):
- return wrapped(*args, **kwargs)
- return _wrapper
- @function_wrapper
- def function():
- pass
- class function_wrapper(object):
- def __init__(self, wrapped):
- self.wrapped = wrapped
- def __call__(self, *args, **kwargs):
- return self.wrapped(*args, **kwargs)
- @function_wrapper
- def function():
- pass
函数(function)自省
当我们谈到一个函数时,通常希望这个函数的属性像其文档上描述的那样,是被明确定义的,例如__name__ 和__doc__ 。
针对某个函数应用装饰器时,这个函数的属性就会发生变化,但这并不是我们所期望的。
- def function_wrapper(wrapped):
- def _wrapper(*args, **kwargs):
- return wrapped(*args, **kwargs)
- return _wrapper
- @function_wrapper
- def function():
- pass
- >>> print(function.__name__)
- _wrapper
- import functools
- def function_wrapper(wrapped):
- @functools.wraps(wrapped)
- def _wrapper(*args, **kwargs):
- return wrapped(*args, **kwargs)
- return _wrapper
- @function_wrapper
- def function():
- pass
- >>> print(function.__name__)
- function
- import inspect
- def function_wrapper(wrapped): ...
- @function_wrapper
- def function(arg1, arg2): pass
- >>> print(inspect.getargspec(function))
- ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)
- >>> print(inspect.getsource(function))
- @functools.wraps(wrapped)
- def _wrapper(*args, **kwargs):
- return wrapped(*args, **kwargs)
包装类方法(@classmethod)
当包装器(@function_wrapper )被应用于@classmethod时,将会抛出如下异常:
- class Class(object):
- @function_wrapper
- @classmethod
- def cmethod(cls):
- pass
- Traceback (most recent call last):
- File "", line 1, in
- File "", line 3, in Class
- File "", line 2, in wrapper
- File ".../functools.py", line 33, in update_wrapper
- setattr(wrapper, attr, getattr(wrapped, attr))
- AttributeError: 'classmethod' object has no attribute '__module__'
然而,在python3下执行,另一个问题出现了:
- class Class(object):
- @function_wrapper
- @classmethod
- def cmethod(cls):
- pass
- >>> Class.cmethod()
- Traceback (most recent call last):
- File "classmethod.py", line 15, in
- Class.cmethod()
- File "classmethod.py", line 6, in _wrapper
- return wrapped(*args, **kwargs)
- TypeError: 'classmethod' object is not callable
总结 - 简单并不意味着正确
尽管大家实现装饰器所用的方法通常都很简单,但这并不意味着它们一定是正确的并且始终能正常工作。
如同上面我们所看到的,functools.wraps() 可以帮我们解决__name__ 和__doc__ 的问题,但对于获取函数的参数(argument)或源代码( source code )则束手无策。