Pre-requisite: this awesome stackoverflow answer on decorators.
I had been trying to learn Flask and came across this nice post. It contains a good introduction to flask in the form of a mini project. While going through the post, I came across this snippet:
@app.route('/') is a decorator which registers the index function to be called when a user makes GET requests to the root page.
I always get the part where we say that a decorator is a function which modifies another function - wraps it with a sort of pre and post functionality. The part of where decorators are passed arguments is what used to confuse me and led me to revisit the afforementioned stackoverflow post
For example, it is easy to understand this:
Output:
Decorator calling func
In the function
Decorator called func
which means that when Python encountered the @ symbol it did an internal equivalent of
func = decorator(func)
which in turn means that a decorator is a function which takes in a function and returns a wrapper over that function and reassigns that wrapper to the original function variable.
This has the side effect of redefining the function name also (func.__name__), to be that of the wrapper function, but as the stackoverflow answer mentions functools.wraps comes to the rescue.
What used to stall me were these kind of examples:
Output:
func1 args - [this, that]
func2 called_from_line:31 args - [who, what]
For func1 our logging is not as verobse as func2 which has 'debug' log level. This is possible because the decorator creating function takes an argument which decides logging behavior (whether to print line no. of caller or not).
The magic of closures is also involved because the decorator and the wrapped function remember the original environment that they were bound with (for func1 the variable loglevel is set to 'info' in wrapped_around_func and for func2, it is set to 'debug')
But what is the deal with the nesting of functions?