Python decorator is applied only once
In Python, function decorators are often applied so that it can add more logic to decorated function whenever the decorated function is called. However, depending on what a decorator returns, the decorating function may not do anything when its decorated function is later called as in the code below.
while every call to func2 calls its decorating function, calls to func1 don’t, except for the first one.
Get J’s stories in your inbox
Join Medium for free to get updates from this writer.
what @syntax did is (adding @syntax is the same as doing):
- func1 = function_logger(func1)
- func2 = call_counter(func2)
Both function logger decorator and call_counter are called only once. function_logger(func) returns decorated func, thus func=func. call_counter(func) returns decorate function, thus func=decorate.
After this, name func1 still points to the same object, but when func2 is later called, decorate is called instead because name func2 points to decorate object now. Where is original func2? It is passed to decorate in its enclosing scope, which is one of the ways for functions to remember their states.
original func2(‘func’) is one of the free variables(‘call’,’decorate’,’func’) as printed.







