Get introduced to decorating or wrapping a function in Python.

What is a decorator?

A decorator is a callable that permits simple modifications to other callable objects. We have multiple callable objects in Python, e.g., functions, methods, and classes. In this lesson, we will only discuss decorating or wrapping a function.

For example, if we have a decorator my_decorator and a function f as follows:

def my_decorator(function):
    # Modify the passed function
    return function

def f():
    return 'Welcome to Educative'

You can notice that my_decorator is a function that takes function as a parameter. It does some modification, and returns the modified function at the end. We can decorate (wrap) f with my_decorator as follows:

f = my_decorator(f)

Instead of calling decorator and assigning f with the modified function, Python provides a syntax that can be used to decorate functions more easily.

def f():
    return 'Welcome to Educative'

Applying a decorator

Now that you are familiar with the syntax, let’s run an executable.

Get hands-on with 1200+ tech skills courses.