How do I nicely write a decorator?
In particular issues include: compatibility with other decorators, preserving of signatures, etc.
I would like to avoid dependency on the decorator module if possible, but if there were sufficient advantages, then I would consider it.
Related
Use functools to preserve the name and doc. The signature won't be preserved.
Directly from the 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With