Member-only story
Understand Python Decorators in 3 Minutes
Extend the functionality of methods and classes with decorators

Decorators provide a readable way of extending the functionality of a function, method, or class from outside of it. Using decorators is especially useful when decorating (i.e. extending) similar functions to do the exact same thing without adding unnecessary repetition in your code.
Here is an example of how to extend a function with a decorator:
@guard_zero
def divide(x, y):
return x / y
The @guard_zero
decorator extends the functionality of the divide
method to ensure that no divisions are made by 0
. However, at this point, there is no such thing as guard_zero
because you haven’t implemented it yet. In the next section, I’m going to show you exactly how to do it.
How To Create a Decorator in Python
The best way to demonstrate decorators in action is by creating one and using it. Let’s implement the @guard_zero
decorator.
In the beginning, you only have this method that divides two numbers:
def divide(x, y):
return x / y
The issue with this method is that there is no check for whether the value y
is 0
. You could obviously solve the issue with a little if
check. But there is an alternative: decorators.
Let’s start by creating a guard_zero
decorator:
A decorator is like a regular function in Python. All it does is accept the operate
function as an argument. Then it extends the functionality of operate
by creating an inner function and adding the extended behavior there. Finally, it returns the inner
function, which is now a new version of the operate
function.
At this point, the guard_zero
decorator is ready. You can now extend (i.e. decorate) the divide
function like this:
divide = guard_zero(divide)