Globals in nested functions
Duncan Booth
duncan.booth at invalid.invalid
Thu Jun 21 08:01:16 EDT 2007
"jm.suresh at no.spam.gmail.com" <jm.suresh at gmail.com> wrote:
> def f():
> a = 12
> def g():
> global a
> if a < 14:
> a=13
> g()
> return a
>
> print f()
>
> This function raises an error. Is there any way to access the a in f()
> from inside g().
>
> I could find few past discussions on this subject, I could not find
> the simple answer whether it is possible to do this reference.
>
'global' means global to the module, it prevents the lookup happening in
current or nested scopes.
Simple answer:
You can access an object referenced by a nested scope variable and you
can mutate the object accessed in that way, but you cannot rebind the
name to a different object without resorting to hackery.
To get the effect you want, simply use a mutable object:
>>> def f():
class v:
a = 12
def g():
if v.a < 14:
v.a=13
g()
return v.a
>>> f()
13
and as soon as the code starts looking at all complex, refactor that so
the class is the thing you interact with:
>>> class F(object):
def g(self):
if self.a < 14:
self.a = 13
def __call__(self):
self.a = 12
self.g()
return self.a
>>> f = F()
>>> f()
13
More information about the Python-list
mailing list