Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice Python Decorators

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

  • Preserving signatures of decorated functions - much more specific question. The answer here is to use the third-party decorator module annotating the decorator with @decorator.decorator
like image 774
Casebash Avatar asked Mar 27 '26 03:03

Casebash


1 Answers

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'
like image 150
3 revsCasebash Avatar answered Mar 28 '26 15:03

3 revsCasebash