decorators and closures

Andrea Crotti andrea.crotti.0 at gmail.com
Mon Nov 21 12:17:12 EST 2011


On 11/21/2011 05:11 PM, Dave Angel wrote:
>
> You didn't mention what version of Python you're running.  With Python 
> 2, I got very different results.  So I switched to Python 3.2, and I 
> still don't get exactly what you have.
>
> A closure is needed if there's some non-global data outside the 
> function definition (code object) that's needed by the function 
> object.  As you supply the code I don't need a closure.  But if I add 
> a local variable in test_decorate(), and refer to it in dec(), then I 
> get one.  Not the same as yours.
>
> You left out the import and the definition line for test_decorate.  
> Did you leave anything else?  And what version of Python are you 
> using?  Are you perhaps running in a shell, as opposed to running code 
> directly from a source file?

I use python 2.7, and actually the whole source is this (test_decorate.py):

def dec(fn):
   def _dec():
       fn()

   return _dec

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

fun()


Using ipython:
import test_decorate
dis.dis(test_decorate)



More information about the Python-list mailing list