Skip to content
PythonAdvanced Python Building Blocksbeginner22 min read

Decorators

Understand function wrapping, the @ syntax, arguments, return values, functools.wraps, and parameterized decorators.

In this lesson, you will learn

  • ✓Explain how decorators use functions as arguments and return wrapped functions.
  • ✓Understand the relationship between @decorator syntax and explicit function decoration.
  • ✓Write wrappers that accept arbitrary positional and keyword arguments.
  • ✓Preserve a decorated function's return value and understand what happens when a wrapper omits return.
  • ✓Use functools.wraps to preserve useful function metadata.
  • ✓Create a decorator that accepts its own configuration arguments.
  • ✓Recognize common decorator mistakes and trace decorated function calls.

1. Understand the Idea Behind Decorators

A decorator is a callable that takes another callable and returns a callable, often a wrapper that adds behavior around the original function.

To understand decorators, first remember that functions can be assigned to variables. If `def greet():` defines a function, then `another_name = greet` makes another reference to the same function object. The function is not called until you write parentheses, such as `greet()`.

A function can also accept another function as an argument and return a new function. This is the foundation of decorators.

A wrapper is a function defined inside another function. It can perform an action, call the original function, and then perform another action. The outer decorator returns the wrapper so that it can be used in place of the original function.

Decorators are useful when the same additional behavior is needed by multiple functions. Instead of duplicating logging, timing, or other cross-cutting behavior in every function body, you can define it once and apply it where needed.

Functions can be assigned to other names

Functions can be assigned to other names
python
def greet():
print('Hello')
 
another_name = greet
another_name()
Output
Hello

`greet` refers to a function object. `another_name = greet` assigns another reference to that function. It does not call the function because there are no parentheses. `another_name()` calls the function, so `Hello` is displayed.

Note

The wrapper in this first example accepts no arguments because the original task function also accepts no arguments. Later examples will show how to write wrappers that work with different function signatures.

2. The @decorator Syntax

Python provides a convenient syntax for applying a decorator. Place `@announce` directly above a function definition to decorate that function.

For a simple decorator, `@announce` above `def task():` is conceptually equivalent to defining the function and then writing `task = announce(task)`. The original function is passed to the decorator, and the returned callable is bound to the function's name.

The decorator is applied when the decorated function definition is executed, typically as the module is imported or when execution reaches that definition. The wrapper's body normally runs later, when the decorated function is called.

This distinction is important: applying a decorator and calling the resulting function are two different events.

Apply a decorator using @ syntax

Apply a decorator using @ syntax
python
def announce(function):
def wrapper():
print('Starting')
return function()
return wrapper
 
@announce
def task():
print('Work')
 
task()
Output
Starting Work

Python defines `announce` first. When the decorated task definition is executed, Python passes the original task function to `announce`. The returned wrapper becomes the object bound to the name `task`. The final `task()` call executes the wrapper and then the original function.

3. Why Wrappers Need *args and **kwargs

The first wrapper used `def wrapper():`, which only accepts calls with no positional or keyword arguments. If the decorated function needs arguments, calling it through this wrapper can raise TypeError.

To make a general-purpose wrapper, use `*args` to collect positional arguments into a tuple and `**kwargs` to collect keyword arguments into a dictionary.

The wrapper can forward both collections to the original function with `function(*args, **kwargs)`. This allows the wrapper to support many different function signatures without listing every parameter separately.

The wrapper should normally return the result of the original function when callers are expected to receive that result. If it calls the original function but does not return the result, the decorated call returns None unless the wrapper returns something else.

Using `*args` and `**kwargs` does not mean that every argument is valid for the original function. Python still checks the original function's signature when the wrapper calls it.

A wrapper that accepts arguments

A wrapper that accepts arguments
python
def announce(function):
def wrapper(*args, **kwargs):
print('Calling function')
return function(*args, **kwargs)
return wrapper
 
@announce
def add(a, b):
return a + b
 
print(add(3, 4))
Output
Calling function 7

`add(3, 4)` passes two positional arguments to the wrapper. `args` contains the values `(3, 4)`, and `kwargs` is an empty dictionary. `function(*args, **kwargs)` forwards the arguments to the original add function. The original function returns 7, and the wrapper returns that value to the caller.

Caution

When writing a wrapper, forward arguments to the original function and return its result unless you intentionally want to change the function's calling behavior or return value.

4. Preserve Function Metadata with functools.wraps

A decorated function is often replaced by a wrapper. Without additional care, attributes such as the function's name and docstring can describe the wrapper instead of the original function.

Python provides `functools.wraps` to help preserve important metadata from the wrapped function. Import it from functools and apply `@wraps(function)` directly above the wrapper definition.

This is useful for debugging, documentation, logging, and tools that inspect functions. For example, without wraps, `greet.__name__` will usually be `wrapper` in a basic decorator. With wraps, it retains the original function's name.

`functools.wraps` does not make the wrapper's implementation identical to the original function. It copies or updates selected metadata and sets `__wrapped__` to reference the wrapped callable, which supports introspection.

Use `wraps` as a standard practice when implementing ordinary function decorators unless you have a specific reason not to.

Preserve the original function's name

Preserve the original function's name
python
from functools import wraps
 
def announce(function):
@wraps(function)
def wrapper(*args, **kwargs):
print('Calling')
return function(*args, **kwargs)
return wrapper
 
@announce
def greet(name):
'''Return a greeting.'''
return f'Hello, {name}!'
 
print(greet.__name__)
print(greet.__doc__)
Output
greet Return a greeting.

`wraps(function)` copies selected metadata from the original function to the wrapper. `greet.__name__` reports `greet` rather than `wrapper`. `greet.__doc__` retains the original function's docstring. The decorator can still add behavior when greet is called; preserving metadata does not remove the wrapper.

Note

Use `@wraps(function)` inside the decorator, immediately above the wrapper definition. It receives the original callable, not the wrapper.

5. Create a Decorator with Its Own Arguments

A regular decorator receives the function being decorated. Sometimes you also want to configure the decorator, such as specifying a message or the number of times an action should be repeated.

A parameterized decorator adds another function layer. The outer function receives the configuration value and returns the actual decorator. That decorator receives the original function and returns the wrapper.

This creates three conceptual levels: configuration, decoration, and execution. Keeping these levels separate makes nested functions easier to understand.

When the decorator accepts a message, for example, the configuration function stores that message in the enclosing scope. The wrapper can then use the message when the decorated function is called.

A decorator with a custom message

A decorator with a custom message
python
from functools import wraps
 
def announce(message):
def decorator(function):
@wraps(function)
def wrapper(*args, **kwargs):
print(message)
return function(*args, **kwargs)
return wrapper
return decorator
 
@announce('Starting task')
def task():
print('Working')
 
task()
Output
Starting task Working

`announce('Starting task')` calls the outer function with a configuration message. The outer function returns `decorator`, which then receives the task function. `decorator` returns the wrapper, which is bound to the name task. When task is called, the wrapper prints the stored message and calls the original function. The original function prints Working.

Note

The `@announce('Starting task')` syntax is equivalent in effect to applying the decorator returned by `announce('Starting task')` to the function definition.

6. Practical Decorators and Common Pitfalls

Decorators are commonly used for logging, timing, caching, access control, and framework features such as registering routes. Their purpose is to keep reusable behavior separate from the function's main task.

A timing decorator, for example, can record the time before and after a function call. A logging decorator can report that a function is being called. These examples illustrate patterns; production implementations may need additional handling for asynchronous functions, exceptions, and concurrency.

A decorator that returns a wrapper changes the callable bound to the decorated name. This matters when inspecting metadata, testing functions, or applying multiple decorators.

If multiple decorators are applied, the one closest to the function is applied first. For example, `@first` above `@second` is conceptually equivalent to `function = first(second(function))`.

A wrapper can also use try/finally to perform cleanup or log completion even when the wrapped function raises an exception. If the wrapper catches an exception, it should do so deliberately and avoid hiding failures unexpectedly.

Log before and after a function call

Log before and after a function call
python
from functools import wraps
 
def log_call(function):
@wraps(function)
def wrapper(*args, **kwargs):
print('Before call')
try:
return function(*args, **kwargs)
finally:
print('After call')
return wrapper
 
@log_call
def multiply(a, b):
print('Multiplying')
return a * b
 
print(multiply(3, 4))
Output
Before call Multiplying After call 12

The wrapper prints Before call before invoking the original function. The original function prints Multiplying and returns 12. The finally block prints After call whether the wrapped function returns normally or raises an exception. Because the wrapper returns the function result, the final print displays 12. If the original function raises an exception, this wrapper still prints After call and then propagates the exception unless another handler catches it.

Caution

Do not silently swallow exceptions or discard return values in a decorator unless that behavior is intentional. Keep wrappers focused and use functools.wraps to preserve useful metadata.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Calling the original function inside the decorator and returning its result instead of returning a wrapper.

Why it happens: A decorator should return a wrapper function when it needs to add behavior around later calls; calling the original immediately executes it during decoration.

Incorrect Approach
script.py
python
Calling the original function inside the decorator and returning its result instead of returning a wrapper.
Correct Solution
script.py
python
Return the wrapper function itself when the goal is to add behavior each time the decorated function is called.

Key takeaway: Return the wrapper function itself when the goal is to add behavior each time the decorated function is called.

#2 Defining wrapper() without arguments when the original function accepts arguments.

Why it happens: A wrapper must accept and forward the arguments supported by the decorated function, often using *args and **kwargs.

Incorrect Approach
script.py
python
Defining wrapper() without arguments when the original function accepts arguments.
Correct Solution
script.py
python
Use `*args` and `**kwargs` and forward them to the wrapped function when you need a general-purpose wrapper.

Key takeaway: Use `*args` and `**kwargs` and forward them to the wrapped function when you need a general-purpose wrapper.

#3 Forgetting to return the wrapped function's result.

Why it happens: If callers depend on the original return value, the wrapper must return the result of calling the wrapped function.

Incorrect Approach
script.py
python
Forgetting to return the wrapped function's result.
Correct Solution
script.py
python
Use `return function(*args, **kwargs)` when callers should receive the original function's return value.

Key takeaway: Use `return function(*args, **kwargs)` when callers should receive the original function's return value.

#4 Forgetting functools.wraps.

Why it happens: functools.wraps preserves useful metadata such as the wrapped function's name, docstring, and __wrapped__ reference.

Incorrect Approach
script.py
python
Forgetting functools.wraps.
Correct Solution
script.py
python
Apply `@wraps(function)` above the wrapper definition to preserve useful metadata and improve introspection.

Key takeaway: Apply `@wraps(function)` above the wrapper definition to preserve useful metadata and improve introspection.

#5 Confusing decorator configuration with the decorated function.

Why it happens: A decorator factory configures a decorator, while the decorator itself receives the function that will be wrapped.

Incorrect Approach
script.py
python
Confusing decorator configuration with the decorated function.
Correct Solution
script.py
python
For parameterized decorators, separate the outer configuration function, the decorator function, and the wrapper function.

Key takeaway: For parameterized decorators, separate the outer configuration function, the decorator function, and the wrapper function.

#6 Assuming decorators run only when the decorated function is called.

Why it happens: The decorator expression is applied when the function is defined, usually at module import or class creation time; the wrapper runs when called.

Incorrect Approach
script.py
python
Assuming decorators run only when the decorated function is called.
Correct Solution
script.py
python
The decorator is applied when the decorated definition executes; the wrapper normally runs when the resulting callable is invoked.

Key takeaway: The decorator is applied when the decorated definition executes; the wrapper normally runs when the resulting callable is invoked.

#7 Assuming stacked decorators execute in the order they appear from top to bottom.

Why it happens: Stacked decorators are applied from the closest decorator to the function outward, so the topmost decorator wraps the result of the one below it.

Incorrect Approach
script.py
python
Assuming stacked decorators execute in the order they appear from top to bottom.
Correct Solution
script.py
python
Decoration is applied from the bottom upward, while wrapper execution follows the resulting nesting order.

Key takeaway: Decoration is applied from the bottom upward, while wrapper execution follows the resulting nesting order.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a decorator in Python?
Answer:
A decorator is a callable that takes another callable and returns a callable, often a wrapper that adds behavior around the original function. It allows reusable behavior to be applied without changing the original function's core implementation.
Q2:How does @decorator syntax work?
Answer:
For a simple decorator, `@decorator` above a function definition is conceptually equivalent to defining the function and then assigning `function = decorator(function)`. The decorated name refers to the callable returned by the decorator.
Q3:Why should a wrapper use *args and **kwargs?
Answer:
They allow the wrapper to accept arbitrary positional and keyword arguments and forward them to the original function. This makes the decorator usable with many different function signatures.
Q4:Why should a wrapper return the original function's result?
Answer:
Without returning the result, a wrapper can discard a useful value. If the wrapper reaches its end without returning anything, the decorated call returns None, even if the original function returned a value.
Q5:What does functools.wraps do?
Answer:
It preserves selected metadata from the wrapped function, including its name and docstring, and sets the wrapper's `__wrapped__` reference. This improves documentation, debugging, and introspection.
Q6:What is a parameterized decorator?
Answer:
A parameterized decorator accepts configuration, such as a message or setting, before receiving the function. It usually has an outer configuration function, an inner decorator, and a wrapper.
Q7:In what order are stacked decorators applied?
Answer:
Decorators are applied from the bottom upward. For `@first` above `@second`, the result is conceptually `first(second(function))`. Calls then pass through the resulting nested wrappers.
Q8:Can a decorator handle exceptions?
Answer:
Yes. A wrapper can use try/except to handle selected exceptions or try/finally to perform cleanup or logging. It should not hide errors unintentionally; exceptions should propagate when that is the intended behavior.
Q9:Name some practical uses of decorators.
Answer:
Common uses include logging, execution-time measurement, caching, access control, validation, and registering functions with frameworks. The best implementation depends on the behavior required and whether the wrapped callable is synchronous or asynchronous.
Q10:What is a common mistake when writing a decorator?
Answer:
Common mistakes include returning the result of the function instead of returning a wrapper, failing to forward arguments, forgetting to return the wrapped function's result, and omitting functools.wraps when metadata preservation is important.

Key takeaways

  • Functions are objects that can be passed to and returned from other functions.
  • A decorator commonly returns a wrapper that adds behavior around an original callable.
  • The @decorator syntax applies a decorator when the decorated definition executes.
  • Use *args and **kwargs to forward positional and keyword arguments when the wrapper needs a flexible signature.
  • Return the wrapped function's result when callers should receive it.
  • Use functools.wraps to preserve useful metadata and support introspection.
  • Parameterized decorators use an additional function layer to capture configuration.
  • Stacked decorators are applied from the bottom upward.
  • Use try/finally for completion or cleanup behavior that must run even when the wrapped function raises.
  • Decorators are useful for reusable concerns such as logging, timing, caching, and access control.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: