I am creating a little helper tool. It is a timer decorator (not so special) for measuring the execution times of any method.
It prints the calculated execution time on the console with useful informations.
def timer(func):
"""@timer decorator"""
from functools import wraps
from time import time
def concat_args(*args, **kwargs):
for arg in args:
yield str(arg)
for key, value in kwargs.items():
yield str(key) + '=' + str(value)
@wraps(func) # sets return meta to func meta
def wrapper(*args, **kwargs):
start = time()
ret = func(*args, **kwargs)
dur = format((time() - start) * 1000, ".2f")
print('{}{}({}) -> {}ms.'.format(
func.__module__ + '.' if func.__module__ else '',
func.__name__,
', '.join(concat_args(*args, **kwargs)),
dur
))
return ret
return wrapper
This gives me the modelname, and the functionname like that:
user.models.get_matches(demo) -> 24.09ms.
I want to have the class name in the output, too:
user.models.User.get_matches(demo) -> 24.09ms.
How can I get the class name of the function ('func') from inside the wrapper?
Edit: Great thanks to Hao Li. Here is the finished version:
def timer(func):
"""@timer decorator"""
from functools import wraps
from time import time
def concat_args(*args, **kwargs):
for arg in args:
yield str(arg)
for key, value in kwargs.items():
yield str(key) + '=' + str(value)
@wraps(func) # sets return meta to func meta
def wrapper(*args, **kwargs):
start = time()
ret = func(*args, **kwargs)
dur = format((time() - start) * 1000, ".2f")
print('{}{}({}) -> {}ms.'.format(
func.__module__ + '.' if func.__module__ else '',
func.__qualname__,
', '.join(concat_args(*args, **kwargs)),
dur,
))
return ret
return wrapper
Try to use func.__qualname__
instead of func.__name__
.
Try to use func.im_class.__name__
to get the name of the class.
Reference: PEP 3155
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