Decorators in python - Part 1
Decorators in python is very useful in data hiding and performing pre and post operation using simple function object. Below is a example of decorator and how its working in python interpretor.
In python everything is object so what we are doing above is adding a syntatical sugar using a decorator that replaces the sample_function object with newly created sample_function object. We have created sample_function object which is passed to function which has another function in inner-scope this function object wrapper is returned. Effectively we have returned the function object and its states to caller. When calling this function object it can access its local variables and func object passed as parameter because these variables are part of the local stack of the wrapper object. Python uses a concept called closure which is a property that refers the variable of the outerscope function including func object passed to sample_decorator
Every time we cant able to write the code using wrapper function like above so effectively we add the syntatical sugar with the actual function itself so below code @sample_decorator.
which expands the code like what we have done in the __main__.
The above code wont work for generic function for example what happens when I can call a function with two parameters or multiple parameters for that we can create a generic decorator like below extending the above code.
So we have packed and unpacked the arguments while passing to decorators.
How can I use a decorator in practical, I can use to write my own logging function that acts as a decorator so this code below is logger function.
Above logging function can be used as a decorator which will write the logs to the logging.txt and then calls the function capture its return value and put it in log file with time when the function executed.
Hope this article helps if you need more like this put a like or comment.
Next I will cover how to write a class decorator and decorator stacking.
Comments
Post a Comment