🎨

How to Use Decorators in Python

PythonAdvanced

Modify function behavior with decorators.

Code Example

Python
# Simple decorator
def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

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

say_hello()

# Decorator with arguments
def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

print("\nRepeated:")
greet("Alice")

# Decorator with return value
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end-start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(0.1)
    return "Done"

print(f"\nResult: {slow_function()}")

# Preserve function metadata
from functools import wraps

def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@logger
def add(a, b):
    """Add two numbers"""
    return a + b

print(f"\nName: {add.__name__}")
print(f"Doc: {add.__doc__}")

Explanation

Decorators wrap functions to add behavior. Use @decorator syntax. Use @wraps to preserve metadata. Can accept arguments with nested functions.

Related Tutorials