Member-only story
Turn Your Python Function into a Decorator with One Line of Code
A new way to write shorter, clearer, and more readable Python decorators that also act as a context manager
Do you want to write a decorator but can’t remember the syntax? Decorators have a pretty difficult syntax that involves a lot of boilerplate code. In this article we’ll demonstrate a simpler way of writing decorators. This new way will be much shorter, clearer, and more readable. Let’s code!
The default way to create a decorator
The code below is the default way to create a decorator. It times how long a decorated function runs. Check out this article for a deep dive in decorators.
def timer(name:str) -> Callable:
def decorator(func:Callable) -> Callable:
@wraps(func)
def decorator_implementation(*args, **kwargs):
try:
print(f"TIMER: {name} start")
strt = time.perf_counter()
return func(*args, **kwargs)
finally:
print(f"TIMER: {name} finished in {time.perf_counter() - strt}")
return decorator_implementation
return decorator
This way we can use our code like this:
@timer(name="test")
def…