Skip to content

Instantly share code, notes, and snippets.

@iancharters
Created November 22, 2021 03:12
Show Gist options
  • Save iancharters/9c03f42dcd0e1e085d9af19c6a8e2326 to your computer and use it in GitHub Desktop.
Save iancharters/9c03f42dcd0e1e085d9af19c6a8e2326 to your computer and use it in GitHub Desktop.
Demonstrating that wrapping a decorating in a decorator and only using functools wraps on the inner decorator will still preserve metadata
import time
from functools import wraps
def conditional_decorator(decorator, condition):
"""
Used to conditionally decorate a function.
"""
def wrapped_decorator(func):
if not condition:
return func
return decorator(func)
return wrapped_decorator
def timethis(func):
"""
Decorator that reports the execution time.
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result
return wrapper
if __name__ == "__main__":
@conditional_decorator(timethis, False)
def countdown(n: int):
"""
Counts down
"""
while n > 0:
n -= 1
countdown(100000)
print("Name:", countdown.__name__)
print("Docstring:", repr(countdown.__doc__))
print("Annotations:", countdown.__annotations__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment