Stop Using Python Decorators Redundantly
How to set a decorator on every child class function from the parent class
decorators are one of the powerful and useful tools in Python as they allow us to modify the behavior of a class or function. Decorators usually take a function as an argument and call it inside another function, which is usually known as a
input_args function is used to print the arguments and returns the output of the function called.
But what if we need to call on every function of a class, it could create a redundancy as mentioned in the below code snippet.
To avoid this redundancy, we could use another powerful tool provided to us by Python’s
MetaClass will help us to modify the function definitions of the child class which will reduce redundant calls to our decorator function.
Let’s look at how…
Parent class will have the logic of setting our
decorator to all the functions of a base class.
So, our final script would be something like the below:
MetaClass Parent is now our weapon which can be inherited in any class where we want our decorator to be used.
I hope this explanation was useful. What are your thoughts on the usage of
metaclass? Do you think there is another easier or better syntax? Share your thoughts and experiences below!