close
Cart icon
User menu icon
User icon
Lightbulb icon
How it works?
FAQ icon
FAQ
Contact icon
Contact
Terms of service icon
Terms of service
Privacy policy icon
Privacy Policy
What role do decorators play in Python programming?

Python - Decorators

In this article, we'll explain what decorators are in Python and what function they serve. We'll start by explaining the decorator's definition and then move on to a simple example. To understand the article, you need basic knowledge of the Python language.

Why are decorators considered a powerful tool in Python development?

The ultimate Python learning experience - learn Python, once and for all.

Learn more

What is a decorator

A decorator in Python is a special function that "wraps" another function or method and allows you to modify its behavior without changing the function's body itself. You can think of it as adding an additional layer (decoration) to an existing function.

Example

Take a look at a simple example of a decorator:

def my_decorator(func):
    def wrapper():
        print("Before func.")
        func()
        print("After func.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

The script's output is as follows:

Before func.
Hello!
After func.

Explanation of the script's operation:

  • We define the function my_decorator(). This function takes another function func as an argument.
  • Inside my_decorator(), we define another function - wrapper(). The wrapper() function will "wrap" the func() function.
  • wrapper() first executes some code before calling the original func(), in this case, printing text before the call.
  • Then, wrapper() calls func(), which is the original function we want to decorate.
  • After calling func(), wrapper() executes more code, printing text after the function call.
  • my_decorator() returns wrapper() as the result. Now, wrapper() is a "decoration" for our original function.
  • We decorate the say_hello() function using my_decorator(). We do this using the @ symbol before the say_hello() function's definition.
  • When calling say_hello(), we actually call wrapper(), which adds additional behavior before and after calling say_hello().
Is understanding decorators essential for Python developers?

The ultimate Python learning experience - learn Python, once and for all.

Learn more

Decorators are powerful tools in Python, allowing flexible modification of functions. They enable adding functionality to existing functions "from the outside" without altering their internal implementation.