decorators and closures

Andrea Crotti andrea.crotti.0 at gmail.com
Mon Nov 21 09:44:34 EST 2011


With one colleague I discovered that the decorator code is always 
executed, every time I call
a nested function:

def dec(fn):
     print("In decorator")
     def _dec():
         fn()

     return _dec

def nested():
     @dec
     def fun():
         print("here")

nested()
nested()

Will give:
In decorator
In decorator

So we were wondering, would the interpreter be able to optimize this 
somehow?
I was betting it's not possible, but I'm I would like to be wrong :)



More information about the Python-list mailing list