51π
β
You may want to use wraps
from functools
. See the example
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
... def wrapper(*args, **kwargs):
... print('Calling decorated function')
... return f(*args, **kwargs)
... return wrapper
...
>>> @my_decorator
... def example():
... """Docstring"""
... print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
π€Tommaso Barbugli
100π
functools.wraps is not needed! Just use func.__name__
import time
def timeit(func):
def timed(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
print('Function', func.__name__, 'time:', round((te -ts)*1000,1), 'ms')
print()
return result
return timed
@timeit
def math_harder():
[x**(x%17)^x%17 for x in range(1,5555)]
math_harder()
@timeit
def sleeper_agent():
time.sleep(1)
sleeper_agent()
Outputs:
Function math_harder time: 8.4 ms
Function sleeper_agent time: 1003.7 ms
π€Zach Estela
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-Setting default value for Foreign Key attribute in Django
- [Django]-How can I use Django OAuth Toolkit with Python Social Auth?
7π
In addition to functools.wraps
, you can check out the decorator module which was designed to help with this problem.
π€tkerwin
- [Django]-AttributeError: 'module' object has no attribute 'tests'
- [Django]-Django py.test does not find settings module
- [Django]-Table thumbnail_kvstore doesn't exist
- [Django]-How can I use Django permissions without defining a content type or model?
- [Django]-Django 1.11 TypeError context must be a dict rather than Context
- [Django]-How to set True as default value for BooleanField on Django?
3π
Check out functools.wraps. Requires python 2.5 or higher though, if thatβs an issue.
π€meshantz
- [Django]-Reverse for '*' with arguments '()' and keyword arguments '{}' not found
- [Django]-Paginating the results of a Django forms POST request
- [Django]-Django logging of custom management commands
2π
For anyone who needs to access the decorated function name when there are multiple decorators, like this:
@decorator1
@decorator2
@decorator3
def decorated_func(stuff):
return stuff
the functools.wraps
mentioned above solves that.
π€Zevgon
- [Django]-Get current user in Model Serializer
- [Django]-Django template can't see CSS files
- [Django]-Gunicorn, no module named 'myproject
Source:stackexchange.com