Wow, that looks pretty weird, right? This is an ELI5 tutorial so I won't focus much on why we do it like this, the simplest answer is that this is simply how decorators work.
First, we define our decorator named "messenger" as a a function that takes another function as its argument.
Then, inside the decorator we define a "wrapper" function that takes *args and **kwargs. We need to use *args and **kwargs here in order to allow any possible function to be decorated.
The function.__name__ I use on the next line returns the name of the function as a string.
Then we get the output of the function by calling it with *args and **kwargs.
Finally, the wrapper function will return the output, then the messenger function returns the wrapper.
Now, when we call adder and multiplier the @messenger decorator will print the "starting function" and "ending function" lines before and after it runs the function. While defining the decorator itself can be a bit tricky, once defined it is simple to add or remove it from your functions.
If you want to practice, I would suggest turning the timer function from the end of the *args and **kwargs tutorial into a decorator that prints execution times. This can be a very useful decorator to have as it can allow you to quickly add checking for slow function execution on a complex script.
I hope I was able to help you understand decorators a little better. Our next EL15 tutorial will be an introduction to objects in python.
This entry was posted in ELI5, Python, tutorial and tagged Python 3, tutorial. Bookmark the permalink.