Python Decorators with arguments!
I gave a brief introduction over decorators in my previous post. I will truly recommend to check that out.
So lets move on from where we finished.I will like to start by giving a small refresher of a decorator in a simple example below.
The output that we get here is 8. Ummm, Okay..Cool!
For those familiar with django REST framework, you must have seen the @api_view (for function based views :-) decorators which seem to take in parameters ‘method’ when they are passed. Like:
@api_view(method =[“GET”,”POST”])
def my_api(request):
pass
So what if I say that I want to create something similar?? I assume that you would say, “Yeah y not!”.
Let’s start making one.
The thing here to keep in mind is the syntax which we use while we want to pass arguments to our decorator. I would again be providing you with the example first and then start off by explaining the code.
So what happens when we run the above code? Well the answer we get is 15 because adder(2,3) equates to 5 and multiply( by = 3) means multiplied by 3 will make it 3*5=15.
You must be seeing that the syntax is very complex in the first look but as you dig deeper , its just reveals itself very clearly.
What we have done here is that we have added another set of function on top of the original decorator function and passed our arguments to that high level outer function.
Simply said, the arguments passed to the outer level function “multiply” are the ones which you will/would pass to your final decorator call. Also that same argument is used very neatly inside our wrapper function.So just by adding in a simple layer of functions and safely using the arguments defined, one can enhance the power of the decorator defined.
So far so good. Let’s make another move by moving a little more farther on the topic and evaluate of using multiple decorators! Yes you read it right! ;-)
Again, let me show you the code first.
So what’s the output? It’s HI THERE!!HI THERE!!
Hmm, Can you figure it out? I am sure you can, but for those who are still thinking , its easier than what you thought.
I have just used 2 different decorators on my hello_world() function.
The first one duplicates whatever I write and the second one will change the case(lower or upper) of the string passed to my function.
Note:
That being said, I would recommend to keep a check on the type of input and data you are using for the different decorators. Because there may be a case where your code can have a different return type for the inputs you gave and your decorator wasn’t ready to handle it! Don’t do that , else it will break your code.
I hope my second attempt on explaining decorators would have made a good impact on those of you reading till the end.
Check out my older blogs for more stuff and do not forget to give me a heart :-)