2009-09-10 84 views
3

我如何很好地编写装饰器?好的Python装饰器

特别问题包括:与其他装饰的兼容性,签名的保护,等等

我想避免的装饰模块的依赖如果有可能,但如果有足够的优势的话,我会考虑。

相关

回答

5

写一个好的装饰器是没有什么不同,然后写一个很好的功能。这意味着,理想情况下,使用docstrings并确保装饰器包含在您的测试框架中。

您应该在标准库(自2.5开始)中使用decorator库或更好的functools.wraps()修饰器。

除此之外,最好让你的装饰者集中精力和精心设计。如果您的装饰器需要特定参数,请勿使用*args**kw。而填写你所期望的参数,所以代替:

def keep_none(func): 
    def _exec(*args, **kw): 
     return None if args[0] is None else func(*args, **kw) 

    return _exec 

...使用... ...

def keep_none(func): 
    """Wraps a function which expects a value as the first argument, and 
    ensures the function won't get called with *None*. If it is, this 
    will return *None*. 

    >>> def f(x): 
    ...  return x + 5 
    >>> f(1) 
    6 
    >>> f(None) is None 
    Traceback (most recent call last): 
     ... 
    TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 
    >>> f = keep_none(f) 
    >>> f(1) 
    6 
    >>> f(None) is None 
    True""" 

    @wraps(func) 
    def _exec(value, *args, **kw): 
     return None if value is None else func(value, *args, **kw) 

    return _exec 
6

使用functools来保存名称和文档。签名将不会被保留。

直接从doc

>>> from functools import wraps 
>>> def my_decorator(f): 
...  @wraps(f) 
...  def wrapper(*args, **kwds): 
...   print 'Calling decorated function' 
...   return f(*args, **kwds) 
...  return wrapper 
... 
>>> @my_decorator 
... def example(): 
...  """Docstring""" 
...  print 'Called example function' 
... 
>>> example() 
Calling decorated function 
Called example function 
>>> example.__name__ 
'example' 
>>> example.__doc__ 
'Docstring' 
+0

其良好ettiquete使维基回答自己的问题。 – voyager 2009-09-11 14:42:43

+0

确实有道理 – Casebash 2009-09-11 23:34:30