decorators and closures

88888 Dihedral dihedral88888 at googlemail.com
Tue Nov 22 12:03:42 EST 2011


On Monday, November 21, 2011 10:44:34 PM UTC+8, Andrea Crotti wrote:
> 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 :)

I love to use decorators. I did the same things to  functions and structures in c long time ago. I think that  might be  the dark night era in  programming  in the early 90's long long ago. 

Cheers.   



More information about the Python-list mailing list