An Introduction to Decorators in Python
They are useful, trust me
For anyone who has worked with the Django REST Framework, Decorators are something they must have come across.
I know I have said it countless times before for other features but decorators are an extremely important python functionality to have an understanding of and that’s exactly what we will be doing in this article.
So what are decorators? In simple terms, decorators are functions that give “special powers” to your functions. Doesn’t make sense? Let’s walk through an example.
Let’s say I have a simple function that prints “Hello world”
def hello_world():
print('hello world')
hello_world()
Easy, nothing fancy here. But what If I want this function to do more than just print “Hello World”.
What if I want it to print “Hello User” without explicitly hard coding it into the function itself? Can it be done?
Yes it can, Let’s take a look
I will first create a function that will take in our original function as an argument.
def mydecorator(function):
def wrapper():
print('Hello User')
function()
return wrapper