Academic Block

Python DecoratorsGet Certified

What Are Decorators?

A decorator is a function that takes another function as input, adds some extra behavior, and returns a new function. The original function still does its job, but the decorator wraps it with additional code that runs before, after, or around the original call. Decorators are widely used for logging, timing, access control, caching, and many other cross-cutting concerns. Python provides a clean @ syntax so you can apply a decorator without writing an explicit assignment. Once you understand the pattern, many advanced Python features become easier to read and write.

  • Wrapper pattern: a decorator returns a new function that calls the original one.
  • Reusable behavior: the same decorator can be applied to many functions.
  • @ syntax: the convenient way to apply a decorator above a function definition.
  • Common uses: timing, logging, validation, authentication, caching.

Your First Decorator

The simplest decorator is a function that receives another function, defines an inner wrapper, and returns that wrapper. When the decorated function is later called, the wrapper runs instead. Inside the wrapper you can execute code before and after the original function. This pattern is the foundation of every decorator you will write.

Try It: A Greeting Decorator

Click Test My Code. Change the name passed to the function and watch the extra messages appear around the greeting.

What this code does: A decorator named announce prints a message before and after the original function runs. The function greet is wrapped by hand and then called.
def announce(func):
    def wrapper(name):
        print("About to call the function...")
        result = func(name)
        print("Function finished.")
        return result
    return wrapper

def greet(name):
    return f"Hello, {name}!"

greet = announce(greet)
print(greet("Jordan Lee"))

Using the @ Syntax

Writing func = decorator(func) works, but it is easy to forget and looks clumsy. Python therefore provides the @decorator syntax. Placing @announce directly above a function definition is exactly equivalent to the manual assignment. The @ form is preferred in almost all real code because it keeps the decoration visible at the point where the function is defined.

Try It: The Same Decorator with @

Click Test My Code. Notice that the behavior is identical to the previous example, yet the code is cleaner.

What this code does: The identical announce decorator is applied with the @ syntax. The function greet is automatically wrapped when it is defined.
def announce(func):
    def wrapper(name):
        print("About to call the function...")
        result = func(name)
        print("Function finished.")
        return result
    return wrapper

@announce
def greet(name):
    return f"Hello, {name}!"

print(greet("Ava Thompson"))

Decorators That Accept Arguments

Sometimes a decorator itself needs configuration. In that case you write a function that takes the configuration values and returns the actual decorator. The result is a three-level nesting: the outermost function receives the arguments, the middle function receives the target function, and the innermost wrapper performs the work. This pattern is common for decorators that control retries, timeouts, or logging levels.

Try It: A Repeat Decorator

Click Test My Code. Change the number of repetitions and observe the output.

What this code does: A decorator factory repeat accepts a count. It returns a decorator that calls the original function that many times. The @repeat(3) syntax is demonstrated.
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def shout(message):
    print(message.upper())

shout("python is fun")

Preserving Function Metadata with @wraps

When a decorator replaces a function, the original name, docstring, and other metadata are lost. Tools that inspect functions then see the wrapper instead of the real function. The functools.wraps decorator copies the important attributes from the original function onto the wrapper, restoring the expected metadata. Using @wraps is considered best practice for any decorator that will be reused.

Try It: Keeping the Original Name and Docstring

Click Test My Code. Compare the printed name and docstring before and after adding @wraps.

What this code does: A decorator uses @wraps so that the wrapped function keeps its original name and docstring. The demonstration prints both pieces of metadata.
from functools import wraps

def announce(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("Calling function...")
        return func(*args, **kwargs)
    return wrapper

@announce
def calculate_area(length, width):
    """Return the area of a rectangle."""
    return length * width

print(calculate_area.__name__)
print(calculate_area.__doc__)
print(calculate_area(5, 4))

Practical Example: Timing a Function

One of the most common uses of a decorator is to measure how long a function takes to run. A timing decorator records the start time, calls the original function, records the end time, and then prints or logs the difference. The same decorator can be applied to any function without changing its source code, which makes performance checks easy to add and remove.

Try It: Measuring Execution Time

Click Test My Code. The decorator reports how many seconds the slow function needed.

What this code does: A timer decorator measures the wall-clock time of any function it wraps. A deliberately slow function is decorated and called so the timing output can be seen.
import time
from functools import wraps

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_add(a, b):
    time.sleep(0.5)
    return a + b

print(slow_add(10, 25))

Practical Example: Simple Logging

Logging the arguments and the return value of a function is another frequent need. A logging decorator can print or write this information without touching the function body. When you later decide you no longer need the logs, you simply remove the decorator line. This separation of concerns keeps the core logic clean.

Try It: Logging Arguments and Results

Click Test My Code. The decorator shows both the input values and the returned result.

What this code does: A log_calls decorator prints the arguments a function receives and the value it returns. A small calculation function is decorated to demonstrate the behavior.
from functools import wraps

def log_calls(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_calls
def multiply(x, y):
    return x * y

print(multiply(6, 7))

Class-Based Decorators

Decorators do not have to be functions. A class can also act as a decorator if it implements the __call__ method. The class is instantiated with the function to be decorated, and later calls to the decorated name invoke the instance’s __call__ method. Class-based decorators are useful when the decorator needs to keep state across multiple calls.

Try It: A Counter Decorator Written as a Class

Click Test My Code. Each call to the decorated function increments an internal counter that is printed.

What this code does: A class named CountCalls acts as a decorator. It stores the original function and a call counter. Every time the decorated function is invoked, the counter is increased and displayed.
class CountCalls:
    def __init__(self, func):
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call {self.count} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello(name):
    return f"Hi, {name}!"

print(say_hello("Maya"))
print(say_hello("Noah"))
print(say_hello("Liam"))

Common Mistakes with Decorators

Decorators are elegant once understood, yet a few mistakes appear regularly when students first write them. The list below highlights the problems that cause the most confusion and shows how to avoid them.

  • Forgetting to return the wrapper: the decorator must return the inner function; otherwise the original function is replaced by None.
  • Not accepting *args and **kwargs: a rigid parameter list makes the decorator usable only with functions that have exactly the same signature.
  • Omitting @wraps: debugging tools and documentation generators then show the wrapper’s name instead of the original function’s name.
  • Calling the original function too early: the decorator should return a function, not the result of calling the original function immediately.
  • Incorrect nesting for parameterized decorators: the outermost function receives the parameters, the next receives the target function, and only the innermost is the wrapper.
  • Stacking order surprises: when several decorators are applied, they are executed from the bottom upward; the order matters.

Key Takeaways

Decorators give you a clean way to add behavior to functions without modifying their source code. They are one of the most distinctive and powerful features of Python. The points below summarize the essential ideas you will use whenever you write or read decorated code.

  • A decorator is a function that takes a function and returns a new function with extra behavior.
  • The @decorator syntax is equivalent to the manual assignment func = decorator(func).
  • Parameterized decorators are written as a factory that returns the actual decorator.
  • Always use @functools.wraps to preserve the original function’s name and docstring.
  • Practical decorators often measure time, log calls, enforce permissions, or cache results.
  • A class can act as a decorator by implementing the __call__ method.
  • Keep the wrapper flexible with *args and **kwargs so it works with any function signature.

Frequently Asked Questions

The questions below are the ones students ask most often when they first meet decorators. Each answer is short and practical, and each idea appears in one of the examples above. Experiment with the live code boxes to confirm the behavior for yourself.

What is a decorator in Python?

A decorator is a function that takes another function as an argument, adds some extra behavior, and returns a new function. The new function usually calls the original one while doing additional work before or after the call.

What does the @ symbol mean?

The @ syntax is a convenient way to apply a decorator. Writing @decorator above a function definition is exactly the same as writing func = decorator(func) after the definition.

Why should I use @functools.wraps?

Without @wraps the decorated function loses its original name, docstring, and other metadata. @wraps copies those attributes from the original function onto the wrapper so that tools and documentation continue to work correctly.

How do I write a decorator that takes arguments?

Write a function that receives the configuration values and returns the actual decorator. The returned decorator then receives the target function and returns the wrapper. This produces the common three-level nesting.

Can a class be used as a decorator?

Yes. If a class implements the __call__ method, an instance of that class can be used as a decorator. The class is instantiated with the function to be decorated, and later calls invoke __call__.

What are common uses of decorators?

Typical uses include measuring execution time, logging arguments and return values, enforcing authentication or permissions, caching results, validating inputs, and retrying failed operations.

Do decorators work with methods as well as functions?

Yes. The same decorator patterns work with instance methods, class methods, and static methods. Care is sometimes needed with the self or cls parameter, but the basic technique remains the same.

What happens when I stack several decorators?

Decorators are applied from the bottom up. The decorator closest to the function runs first, and each outer decorator wraps the result of the one below it. The order can change the final behavior, so it should be chosen deliberately.

Ready for the next step?Learn how to manage resources cleanly with the with statement.
Next: Context Managers →