Python Decorators

A decorator is a function that adds or modifies the behavior of another function without changing its original code.

Functions as Objects

Python functions can be stored in variables and passed to other functions.

Python
Pass a function as an argument.
def greet():
    return "Hello"

message = greet
print(message())

Create a Simple Decorator

Python
Add behavior before calling a function.
def logger(func):
    def wrapper():
        print("Function started")
        func()
    return wrapper

@logger
def greet():
    print("Hello!")

greet()

Decorators with Arguments

Use *args and **kwargs when the decorated function can receive different arguments.

Python
Decorator supporting function arguments.
def logger(func):
    def wrapper(*args, **kwargs):
        print("Calling function")
        return func(*args, **kwargs)
    return wrapper

@logger
def add(a, b):
    return a + b

print(add(5, 3))

Using functools.wraps

functools.wraps preserves metadata such as the original function name and documentation.

Python
Preserve function metadata.
from functools import wraps

def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

Common Use Cases

Decorators are commonly used for logging, authentication, timing, caching, validation, and access control.

Summary

Decorators provide a clean way to extend function behavior. The @decorator syntax makes them easy to apply and reuse across multiple functions.