Created
October 26, 2021 17:41
-
-
Save nogsantos/4d65dae34006dc12a12c2858ed933193 to your computer and use it in GitHub Desktop.
Example how to create a python decorator
This file contains 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 time | |
import random | |
from functools import wraps | |
def stopwatch(func_in=None, *, show_time: bool = True, show_name: bool = True): | |
def do(annotated_function): | |
@wraps(annotated_function) | |
def func(*args, **kwargs): | |
tic = time.time() | |
execution = annotated_function(*args, **kwargs) | |
text = "" | |
if show_name: | |
text += f"The function {annotated_function.__name__} " | |
if show_time: | |
text += f"took {round(time.time() - tic, ndigits=3)}ms to be executed" | |
if text: | |
print(text) | |
return execution | |
return func | |
if func_in is None: | |
return do | |
return do(func_in) | |
@stopwatch | |
def sleep_random(n: int = 1) -> str: | |
"""This function sleeps for at least `s` seconds.""" | |
time.sleep( n + random.random() / 100) | |
return "Done!" | |
sleep_random(1), sleep_random(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment