Created
March 2, 2021 16:19
-
-
Save Fifan31/2b40b8743eb25eb99a054211a05ca798 to your computer and use it in GitHub Desktop.
Some python decorators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import time | |
def timer(func): | |
"""Print the runtime of the decorated function""" | |
@functools.wraps(func) | |
def wrapper_timer(*args, **kwargs): | |
start_time = time.perf_counter() # 1 | |
value = func(*args, **kwargs) | |
end_time = time.perf_counter() # 2 | |
run_time = end_time - start_time # 3 | |
print(f"Finished {func.__name__!r} in {run_time:.4f} secs") | |
return value | |
return wrapper_timer | |
def debug(func): | |
"""Print the function signature and return value""" | |
@functools.wraps(func) | |
def wrapper_debug(*args, **kwargs): | |
args_repr = [repr(a) for a in args] # 1 | |
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] # 2 | |
signature = ", ".join(args_repr + kwargs_repr) # 3 | |
print(f"Calling {func.__name__}({signature})") | |
value = func(*args, **kwargs) | |
print(f"{func.__name__!r} returned {value!r}") # 4 | |
return value | |
return wrapper_debug | |
def repeat(_func=None, *, num_times=2): | |
def decorator_repeat(func): | |
@functools.wraps(func) | |
def wrapper_repeat(*args, **kwargs): | |
for _ in range(num_times): | |
value = func(*args, **kwargs) | |
return value | |
return wrapper_repeat | |
if _func is None: | |
return decorator_repeat | |
else: | |
return decorator_repeat(_func) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment