Skip to content
Python

Decorators

Define and use decorators.

By EZ4Code Team
decoratordecorator

Code

import functools
import time

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

@timer
def slow_func():
    time.sleep(1)
    return "done"

# Decorator with arguments
def repeat(n):
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return deco

Explanation

Decorators extend functionality without modifying the original function; functools.wraps preserves metadata.

More Python Snippets