Function creation (what happened?)

Chris Hulan chris.hulan at gmail.com
Fri May 9 08:38:41 EDT 2008


On May 9, 8:25 am, Viktor <alefn... at gmail.com> wrote:
> Can somebody give me an explanation what happened here (or point me to
> some docs)?
>
> Code:
>
> HMMM = None
>
> def w(fn):
>     print 'fn:', id(fn)
>     HMMM = fn
>     print 'HMMM:', id(HMMM)
>     def wrapper(*v, **kw):
>         fn(*v, **kw)
>     wrapper.i = fn
>     print 'wrapper:', id(wrapper)
>     return wrapper
>
> class A:
>     @w
>     def __init__(self): pass
>
> print 'A.__init__:', id(A.__init__)
> print 'A.__init__.i:', id(A.__init__.i)
> print 'HMMM:', id(HMMM)
>
> Output:
>
> fn: 10404208
> HMMM: 10404208
> wrapper: 10404272
> A.__init__: 10376136
> A.__init__.i: 10404208
> HMMM: 505264624
>
> Why did HMMM changed his id?!

The HMMM inside w is local to that function and is not the same HMMM
that is defined just before w.
Have a look at http://docs.python.org/ref/global.html

cheers



More information about the Python-list mailing list