Python Decorators - Part lll
Aman Bhardwaj
Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff
This article is in continuation to my previous two articles on decorators. I would encourage you to read both of those articles before moving on.
The main topic covered in this article is Parameterized Decorators. So, let's begin.
Parameterized Decorators
Before we even talk about parameterized decorators, let us understand why we even need parameterized decorators. To answer this let us revisit the @lru_cache decorator that we know from the previous article again in the below points but from the perspective of a parameterized decorator.
I hope now, you understand that decorators, in addition to changing the behavior of a function also sometimes require control parameters to offer a better environment to augment or change the behavior of a function.
But how to make a decorator accept arguments?
As we know that decorators take the decorated function as an argument and return a closure or a function that replaces the decorated function.
We need to wrap the decorator in another function, which we call the decorator factory. This decorator factory receives those arguments. Let's see the example below:
领英推荐
Output:
Running the decorator factory
Running the decorator function
Running the inner function or the Closure! True
Running the actual decorated function!!
You don't need to invoke the decorator_factory and decorator as shown in the above example, you could simply use what we have been talking about parameterized decorator till now, shown below:
You just used your first parameterized decorator.
Both the examples above will output the same data:
Output:
Running the decorator factory
Running the decorator function
Running the inner function or the Closure! True
Running the actual decorated function!!
Class-based decorator
We can represent the above function-based decorator to the class-based decorators too as shown below:
Output:
Running --> factor
Running --> decorator
Function received : myfunc
Running --> inner: Truey
And this marks the end of our decorator series. I hope you enjoyed and understood these articles. If you liked it, please follow me on Linkedin. See you at the next one.
Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff
2 年Python decorators - Part l: https://www.dhirubhai.net/pulse/python-decorators-part-i-aman-bhardwaj/ Python decorators - Part ll: https://www.dhirubhai.net/pulse/python-decorators-part-ll-aman-bhardwaj/?trackingId=mR39EEppRSOYcRvRfdsAig%3D%3D Because Closures are a pre-requisite to understanding decorators in python, here is the link to its article: https://www.dhirubhai.net/pulse/variable-scoping-closures-python-aman-bhardwaj/