functools

functools 是一个返回函数的函数库.

functools.partial(func[,*args][, **keywords])

返回一个 partial 对象. 该对象被调用时, 执行 func, 元组参数为 args+fargs, 关键字参数为 keywords.update(fkeywords).

实现类似下面的代码:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

wraps

一个 decorator, 使 wrapper 函数看起来像 wrapped 函数. 看起来像是指, __name__, __module__, __doc__ 和 __dict__ 使用 wrapped 函数的值.

>>> def a(): print 'a'
...
>>> def b(): print 'b'
...
>>> wraps(a)(b)                 # 让 b 看起来像 a
<function a at 0x1006ee6e0>
>>> wraps(a)(b)()               # 但其实还是 b
b
>>>
>>> from functools import wraps
>>> def my_decorator(f):
...     @wraps(f)                   # 让 wrapper 看起来像 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'

Without the use of this decorator factory, the name of the example function would have been ‘wrapper’, and the docstring of the original example() would have been lost.