SyntaxStudy
Sign Up
Python Intermediate 10 min read

Decorators

Python Decorators

Decorators wrap functions to add behavior without modifying their code.

Basic Decorator

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before")
        result = func(*args, **kwargs)
        print("After")
        return result
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Practical Example

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Took {time.time()-start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
Pro Tip

Use functools.wraps(func) inside the wrapper to preserve the original function's metadata.