Python decorators are a powerful feature that allows you to modify or extend the behavior of a function, method, or class without changing its original implementation. A decorator receives an object, usually a function, and returns a modified object.
Decorators are widely used for concerns that appear across multiple parts of an application, such as logging, authorization, caching, timing, validation, retries, registration, and transaction handling. Python also provides several built-in decorators, including
@property,
@staticmethod,
@classmethod,
and
@functools.wraps.
Decorators become much easier to understand once you remember one important idea: functions are objects in Python. A function can be stored in a variable, passed to another function, returned from a function, and wrapped by another callable.
What You Will Learn
- What decorators are and how they work
- How to create a basic function decorator
- How wrapper functions intercept calls
- Why functools.wraps is important
- How decorators work with arguments
- How to stack multiple decorators
- How to create decorators that accept configuration
- How decorators can be applied to classes and methods
What Is a Decorator?
A decorator is a callable that takes another callable and returns a callable with modified or extended behavior.
The simplest way to understand this is to start with an ordinary function.
def greet():
print("Hello, Python")
greet()
A decorator can add behavior around this function without changing the function body itself.
def log_call(func):
def wrapper():
print("Function started")
func()
print("Function finished")
return wrapper
def greet():
print("Hello, Python")
greet = log_call(greet)
greet()
The expression
greet = log_call(greet)
replaces the original function reference with the wrapper returned by the decorator.
Decorator Syntax with @
Python provides a cleaner syntax for applying decorators using the
@
symbol.
def log_call(func):
def wrapper():
print("Function started")
func()
print("Function finished")
return wrapper
@log_call
def greet():
print("Hello, Python")
greet()
The decorator syntax is equivalent to:
def greet():
print("Hello, Python")
greet = log_call(greet)
The
@log_call
syntax is therefore not a special kind of function. It is a convenient way to apply an existing callable transformation to the function defined immediately below it.
How a Decorator Works
1. Define the original function
The function contains the actual business logic.
2. Pass it to the decorator
The decorator receives the function object.
3. Create or return a wrapper
The wrapper adds behavior before, after, or around the original call.
4. Replace the original reference
Calling the decorated function now executes the wrapper.
Decorators with Function Arguments
A wrapper that works with a function accepting arbitrary positional and keyword arguments usually uses
*args
and
**kwargs.
def log_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"Finished {func.__name__}")
return result
return wrapper
@log_call
def add(a: int, b: int) -> int:
return a + b
print(add(10, 20))
Using
*args
and
**kwargs
makes the wrapper flexible enough to forward different argument combinations to the original function.
Preserving Metadata with functools.wraps
A decorator replaces the original function reference with the wrapper. Without additional care, attributes such as the function name and docstring may appear to belong to the wrapper instead of the original function.
The standard library provides
functools.wraps
to copy important metadata from the wrapped function to the wrapper.
from functools import wraps
def log_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_call
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
print(add(10, 20))
print(add.__name__)
print(add.__doc__)
Using
@wraps(func)
is a best practice for most function decorators because introspection, debugging, documentation tools, and frameworks can continue to see useful metadata.
Decorators That Return Values
A wrapper should normally return the result of the original function when the original function returns a value.
from functools import wraps
def uppercase_result(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_result
def get_message():
return "hello python"
print(get_message())
Forgetting the
return result
statement is a common decorator bug because callers may unexpectedly receive
None.
Running Code Before and After a Function
One of the most common decorator patterns is to execute logic before and after the wrapped function.
from functools import wraps
def audit(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before execution")
result = func(*args, **kwargs)
print("After execution")
return result
return wrapper
@audit
def process_order(order_id: int):
print(f"Processing order {order_id}")
return True
process_order(101)
This pattern is useful for logging, metrics, tracing, permissions, and similar cross-cutting concerns.
Handling Exceptions in a Decorator
A decorator can also surround a function call with exception handling. This can be useful for consistent logging or translating errors, but the decorator should not silently hide failures.
from functools import wraps
def log_errors(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as error:
print(
f"{func.__name__} failed: {error}"
)
raise
return wrapper
@log_errors
def divide(a: float, b: float) -> float:
return a / b
try:
divide(10, 0)
except ZeroDivisionError:
print("Handled by caller")
The decorator records the error and then uses
raise
to preserve the original failure for the caller.
Decorators with Configuration
Sometimes the decorator itself needs arguments. For example, a retry decorator might accept the number of attempts, or a logging decorator might accept a label.
This introduces another layer: the outer function receives the decorator configuration and returns the actual decorator.
from functools import wraps
def repeat(times: int):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name: str):
print(f"Hello, {name}")
greet("Alex")
The structure is:
decorator_arguments
↓
decorator_factory
↓
decorator
↓
wrapper
↓
original_function
Decorators with Optional Configuration
More advanced decorators can support both
@decorate
and
@decorate(...)
forms, but this should only be introduced when there is a real usability benefit. Otherwise, keeping one clear calling style is easier to maintain.
Stacking Multiple Decorators
More than one decorator can be applied to the same function.
from functools import wraps
def first(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("First decorator")
return func(*args, **kwargs)
return wrapper
def second(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Second decorator")
return func(*args, **kwargs)
return wrapper
@first
@second
def greet():
print("Hello")
greet()
Decorators are applied from the function outward. The previous example is equivalent to:
greet = first(second(greet))
The order therefore matters. Reordering decorators can change both execution order and application behavior.
Built-in Decorators
Python provides several decorators that change how methods or classes behave. Some of the most common are
@staticmethod,
@classmethod,
and
@property.
staticmethod
A static method does not receive the instance automatically. It is useful when a function logically belongs to a class but does not need instance or class state.
class Temperature:
@staticmethod
def celsius_to_fahrenheit(
celsius: float
) -> float:
return (celsius * 9 / 5) + 32
print(
Temperature.celsius_to_fahrenheit(25)
)
classmethod
A class method receives the class as
cls.
It is often useful for alternate constructors or operations involving class-level state.
class User:
def __init__(self, name: str):
self.name = name
@classmethod
def from_email(cls, email: str):
username = email.split("@")[0]
return cls(username)
user = User.from_email(
"alex@example.com"
)
print(user.name)
property
The
@property
decorator allows a method to be accessed using attribute syntax.
class Rectangle:
def __init__(self, width: float, height: float):
self.width = width
self.height = height
@property
def area(self) -> float:
return self.width * self.height
rectangle = Rectangle(10, 5)
print(rectangle.area)
Decorating Methods
Regular function decorators can also decorate instance methods. The wrapper receives the instance as part of
args
when the method is called normally.
from functools import wraps
def log_method(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Running {func.__name__}")
return func(*args, **kwargs)
return wrapper
class UserService:
@log_method
def create_user(self, username: str):
return f"Created {username}"
service = UserService()
print(service.create_user("alex"))
Decorating Classes
Decorators are not limited to functions. A class decorator receives a class and can modify or register it before returning it.
def add_label(label: str):
def decorator(cls):
cls.label = label
return cls
return decorator
@add_label("developer")
class User:
def __init__(self, name: str):
self.name = name
user = User("Alex")
print(user.name)
print(user.label)
Class decorators can be useful for registration systems, metadata, framework configuration, and controlled class transformations.
A Logging Decorator
Logging is a common real-world use case because many functions need consistent execution information without duplicating logging code in every function body.
from functools import wraps
import time
def measure_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(
f"{func.__name__} "
f"took {elapsed:.6f} seconds"
)
return result
return wrapper
@measure_time
def calculate_total(values):
return sum(values)
print(calculate_total(range(100000)))
The timing behavior is separated from the business logic. The function remains focused on calculating the total, while the decorator handles measurement.
Caching with a Decorator
Python also provides decorator-based caching utilities in the standard library. For example,
functools.lru_cache
can cache results of functions whose inputs are suitable as cache keys.
from functools import lru_cache
@lru_cache
def fibonacci(n: int) -> int:
if n < 2:
return n
return (
fibonacci(n - 1)
+ fibonacci(n - 2)
)
print(fibonacci(20))
The decorator adds memoization without requiring the caching logic to be manually written inside the recursive function.
Authorization Decorator Pattern
Decorators can also centralize access checks around functions or methods. In production applications, the exact authentication and authorization mechanism depends on the framework and architecture, but the underlying decorator pattern remains useful.
from functools import wraps
def require_admin(func):
@wraps(func)
def wrapper(user, *args, **kwargs):
if user.get("role") != "admin":
raise PermissionError(
"Admin access required"
)
return func(user, *args, **kwargs)
return wrapper
@require_admin
def delete_user(user, user_id: int):
return f"Deleted user {user_id}"
admin = {
"username": "alex",
"role": "admin"
}
print(delete_user(admin, 101))
The authorization rule is separated from the protected operation. This reduces duplication when many operations require the same policy.
Decorators and Closures
Function decorators commonly rely on closures. A nested wrapper function can remember the original function and other values from the surrounding scope even after the outer decorator function has finished running.
def prefix_message(prefix: str):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return f"{prefix}: {result}"
return wrapper
return decorator
@prefix_message("INFO")
def get_message():
return "Application started"
print(get_message())
The wrapper remembers the
prefix
value supplied when the decorator was created. This relationship between nested functions and captured state is an important concept for understanding parameterized decorators.
Decorators and Function Signatures
A generic wrapper using
*args
and
**kwargs
accepts many possible calls, but the wrapper itself does not explicitly describe the original function's signature. Using
functools.wraps
helps preserve metadata, and careful type annotations can make decorated APIs easier to understand.
For libraries and complex applications, decorators should be designed carefully so they do not make function behavior or error messages harder to understand.
Common Mistakes
Forgetting to Return the Wrapper
A decorator must return the modified callable. Forgetting the return statement can replace the decorated function with None.
Forgetting the Original Result
If the original function returns a value, the wrapper should normally return that value unless changing the API is intentional.
Skipping functools.wraps
Without wraps, useful function metadata can be replaced by the wrapper's metadata, making debugging and introspection harder.
Too Many Nested Decorators
Deeply stacked wrappers can make execution order difficult to understand. Keep decorator usage focused and meaningful.
Best Practices for Python Decorators
- Use decorators for behavior that is genuinely reusable across multiple callables.
- Use
functools.wrapsin function wrappers. - Forward
*argsand**kwargswhen the decorator should support general call signatures. - Return the original function's result unless changing the contract is intentional.
- Keep wrappers small and focused on one concern.
- Be deliberate about decorator order when stacking multiple decorators.
- Do not hide important exceptions unless the decorator has a clear error-handling responsibility.
- Avoid using decorators when an ordinary helper function would be simpler and clearer.
- Document decorators that significantly change function behavior.
A Practical Retry Decorator
Retry behavior is another common decorator use case. A generic retry decorator can centralize repeated-attempt logic while allowing the decorated function to remain focused on the operation itself.
from functools import wraps
def retry(attempts: int):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_error = None
for _ in range(attempts):
try:
return func(*args, **kwargs)
except Exception as error:
last_error = error
if last_error is not None:
raise last_error
raise RuntimeError(
"No retry attempts configured"
)
return wrapper
return decorator
@retry(3)
def unstable_operation():
print("Attempting operation")
raise RuntimeError("Operation failed")
try:
unstable_operation()
except RuntimeError as error:
print(error)
Real retry systems usually need additional decisions about which exceptions are retryable, delays, backoff, timeouts, and idempotency. The example demonstrates the decorator mechanism rather than providing a complete production retry policy.
When Should You Use a Decorator?
Decorators are a good fit when the same behavior needs to wrap multiple functions or methods while leaving their core implementations focused on their primary responsibility.
- Logging and tracing
- Execution timing and metrics
- Authorization checks
- Caching and memoization
- Validation and reusable preconditions
- Retries and controlled error handling
- Registration of functions or classes with a framework
When Not to Use a Decorator
A decorator is not automatically the best solution just because behavior can technically be implemented with one. If the wrapper makes the function's behavior surprising, makes debugging difficult, or adds several layers of indirection for a one-time operation, a normal function or explicit method may be clearer.
Good decorator design should reduce duplication without hiding important application behavior from the reader.
Interview Questions to Prepare
- What is a decorator in Python?
- How does the
@decoratorsyntax work? - Why are functions useful for implementing decorators?
- What is a wrapper function?
- Why are
*argsand**kwargscommonly used in decorators? - What does
functools.wrapsdo? - How do decorators accept arguments?
- How does Python apply multiple decorators?
- What is the difference between a decorator and a decorator factory?
- What are common built-in decorators such as
@property,@staticmethod, and@classmethod?
Summary
Python decorators provide a reusable way to extend or modify the behavior of functions, methods, and classes without placing the additional logic directly inside the original implementation. They work because functions are first-class objects that can be passed to and returned from other functions.
The most important decorator concepts are wrapper functions, argument forwarding, closures, metadata preservation with
functools.wraps,
parameterized decorators, and decorator ordering. Once these concepts are clear, decorators such as
@property,
@classmethod,
and
@staticmethod
become much easier to understand. Use decorators when they make repeated cross-cutting behavior clearer and more maintainable, not simply because the language makes them possible.