Decorators

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.

@my_decorator
def f():
    return 'Welcome to Educative'

Applying a decorator

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

Press + to interact
# Implementing a decorator
def my_decorator(func):
def wrapper():
result = func()
result = result.upper()
return result
return wrapper
# Applying the decorator
@my_decorator
def welcome():
return 'Welcome to Educative'
print(welcome())

In the code above, we implement a decorator my_decorator. Look at its header at line 2. It takes func as a parameter. The func function would be decorated. Inside the my_decorator function we design a nested function: ...

Access this course and 1400+ top-rated courses and projects.