Skip to content
UPEEC

Decorators

A decorator wraps a function to add behaviour — like timing, logging or caching — without changing its code.

Intermediate
Comments 0
import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

@timed
def read_all_sensors():
    ...

@timed is shorthand for read_all_sensors = timed(read_all_sensors). Built-in examples: @staticmethod, @property, @functools.lru_cache.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.