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
`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
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
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
`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
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
`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
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
`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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a decorator in Python?
Q2:How does @decorator syntax work?
Q3:Why should a wrapper use *args and **kwargs?
Q4:Why should a wrapper return the original function's result?
Q5:What does functools.wraps do?
Q6:What is a parameterized decorator?
Q7:In what order are stacked decorators applied?
Q8:Can a decorator handle exceptions?
Q9:Name some practical uses of decorators.
Q10:What is a common mistake when writing a decorator?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: