Decorators in python

I can not understand the use of decorators can you help with few more easy examples and few tough ones?

Hi @arjun1,

Image 1


Image 2


Looking at both the images, you can easily infer what @decorator internally doing.

Now coming into some facts, in python, function can be returned and passed as an argument. function can even have its own attributes, see.

So, while programming, programmers found out that there are some situations where when calling some functions you needed to do some other things as a prerequisite. Hence they came up with decorators.

As a real life example, lets say you are designing a web API, while going through the testing process, you found out that, anyone can steal data from your server by passing on URLs of the form “./../data/*”. Hence, you changed all your function calls that took a URL before to a preprocessing step + function_call, i.e, firstly you checked the authenticity of the URL then only you passed it to the function.
There you used decorators instead of changing every function calls.

If you compare that with our example, function decorator did the checking step while the function func took the URLs.

I hope this cleared your doubts regarding python decorators.

Happy Learning :slight_smile:
Thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.