On this page

Decorators

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Understanding Decorators​

A decorator is a Python feature that allows you to wrap one function inside another to add behavior without modifying the original function’s code.

Decorators are essential for:

They are a cornerstone of clean, maintainable Python design.


The Core Idea Behind Decorators​

A decorator is simply a function that:

  1. Accepts another function as input
  2. Returns a new function that adds behavior
  3. Preserves the original function’s interface

Example of a basic decorator:


def my_decorator(func):

    def wrapper():

        print("Before the function runs")

        result = func()

        print("After the function runs")

        return result

    return wrapper

Applying it:


@my_decorator

def greet():

    print("Hello!")

Calling greet() now runs the wrapper around the original function.


Why Use the @ Syntax​

The decorator syntax:


@decorator

def func():

    ...

is equivalent to:


func = decorator(func)

The @ form is clearer, more readable, and standard in professional Python codebases.


Decorators with Arguments​

Most real‑world functions accept parameters, so decorators must handle them too.


def logger(func):

    def wrapper(*args, **kwargs):

        print(f"Calling {func.__name__}")

        return func(*args, **kwargs)

    return wrapper

Usage:


@logger

def add(a, b):

    return a + b

The wrapper uses *args and **kwargs to support any function signature.


Returning Values from Decorated Functions​

Decorators must return the wrapped function’s result.


def double_result(func):

    def wrapper(*args, **kwargs):

        result = func(*args, **kwargs)

        return result * 2

    return wrapper

This pattern is essential for correctness.


Decorators That Accept Their Own Arguments​

Sometimes the decorator itself needs configuration.

Example: a decorator that repeats a function call.


def repeat(times):

    def decorator(func):

        def wrapper(*args, **kwargs):

            result = None

            for _ in range(times):

                result = func(*args, **kwargs)

            return result

        return wrapper

    return decorator

Usage:


@repeat(3)

def say_hi():

    print("Hi")

This pattern uses three layers:

  1. The outer function receives decorator arguments
  2. The middle function receives the function being decorated
  3. The inner function wraps the behavior

Preserving Metadata with functools.wraps​

Decorators replace the original function with the wrapper, which can hide metadata like:

Use wraps to preserve them:


from functools import wraps



def logger(func):

    @wraps(func)

    def wrapper(*args, **kwargs):

        print(f"Calling {func.__name__}")

        return func(*args, **kwargs)

    return wrapper

This is a best practice in all production‑quality decorators.


Stacking Multiple Decorators​

You can apply more than one decorator to a function.


@decorator_a

@decorator_b

def func():

    ...

Execution order:

Decorators stack from bottom to top.


Real‑World Use Cases​

Decorators appear everywhere in modern Python:

Decorators provide clean, declarative syntax for cross‑cutting concerns.


Best Practices​

Professional Python code uses decorators to improve clarity, not obscure logic.


Summary​

Decorators allow you to wrap functions with additional behavior in a clean, reusable, and expressive way.

You learned how decorators work internally, how to handle arguments, how to preserve metadata, how to stack decorators, and how they appear in real‑world applications.

They are one of Python’s most powerful abstraction tools, enabling elegant and maintainable software design.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Generators

Next

Typing & Type Hints