Decorators
Get introduced to decorating or wrapping a function in Python.
We'll cover the following...
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.
# Implementing a decoratordef my_decorator(func):def wrapper():result = func()result = result.upper()return resultreturn wrapper# Applying the decorator@my_decoratordef 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: ...