Python Functions

Python Decorators

Use functools.wraps to preserve the name and doc, but not the signature. From the Python documentation:

>>> 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.__doc__

If you don't mind including the third-party decorator module, you can simply wrap the decorator with @decorator in
to preserve not only the name and doc, but also the signature. You can also use the following method with a decorator_apply function to use a third-party decorator in a signature preserving way.

def decorator_apply(dec, func):
    """Decorate a function by preserving the signature even if dec is not a signature-preserving decorator."""
    return FunctionMaker.create(
        func, 'return decorated(%(signature)s)',
        dict(decorated=dec(func)), undecorated=func)
def my_fixed_decorator(func):
    return decorator_apply(my_decorator, func)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License