TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Member-only story

Turn Your Python Function into a Decorator with One Line of Code

Mike Huls
4 min readMay 23, 2024

--

Decorating made easier (image by Tobias Bjørkli on Pexels)

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…

--

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Mike Huls
Mike Huls

Written by Mike Huls

I write about interesting programming-related things: techniques, system architecture, software design and how to apply them in the best way. — mikehuls.com

Responses (4)