Decorator

A function that wraps another function to add behaviour, applied with the @name syntax above a def.

A decorator is written as @something on the line above a function definition. It takes the function below it and returns a modified version — a clean way to add behaviour without changing the function's own code.

You'll meet decorators most often when using a web framework: Flask's @app.route("/") is a decorator that registers a function as a route.

Example
def shout(func):
    def wrapper(name):
        return func(name).upper()
    return wrapper

@shout                       # wrap greet with shout
def greet(name):
    return f"hello {name}"

print(greet("ada"))
Output
HELLO ADA

Where this shows up in real Python

Decorators add behaviour — logging, timing, access checks, web routing — without editing the function they wrap.

Commonly used Decorator tools

  • @something — apply a decorator to the function below
  • functools.wraps — keep the wrapped function’s name/help
  • @property — a built-in decorator for class attributes
  • @app.route('/') — Flask routing is a decorator

Official documentation: Python Glossary: decorator

Related lessons

Related terms