decorator

In Python, a decorator is a callable that takes another callable as an argument and modifies its behavior without modifying its implementation, returning a new callable.

Decorators are a form of metaprogramming, meaning they allow you to write code that manipulates other code.

Decorators are particularly useful for adding features to your functions, such as logging, authentication, or caching, in a clean and readable manner.

Syntax

Python Syntax
@decorator_name
def decorated_function():
    ...

To apply a decorator to a function, you use the @decorator_name syntax just before the function’s definition. The decorator takes the original function as an argument, processes it, and returns a function object with extended behavior.

Example

Here’s a quick example of using a decorator to log the execution of a function:

Python
>>> def logger(func):
...     def wrapper():
...         print("Something is happening before the function is called.")
...         func()
...         print("Something is happening after the function is called.")
...     return wrapper
...

>>> @logger
... def greet():
...     print("Hello!")
...

>>> greet()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

In this example, @logger is a decorator that wraps the greet() function. When you call greet(), the wrapper function will print messages before and after the call.

Tutorial

Primer on Python Decorators

In this tutorial, you'll look at what Python decorators are and how you define and use them. Decorators can make your code more readable and reusable. Come take a look at how decorators work under the hood and practice writing your own decorators.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 11, 2025 • Reviewed by Leodanis Pozo Ramos