Function creation (what happened?)
Peter Otten
__peter__ at web.de
Fri May 9 08:39:43 EDT 2008
Viktor 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)
This prints the id() of the local (to the function w()) HMMM variable
> 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)
while this prints the id() of the global HMMM variable. Python assumes that
a variable is local to a function if there is an assignment to that
variable anywhere inside that function.
If you want to change the variable (Python-lingo "rebind the name") HMMM
declare it as global in the function:
def w(fn):
global HMMM
# ...
HMMM = fn
# ...
Otherwise I've no idea what you are trying to do here...
Peter
More information about the Python-list
mailing list