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.
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():
a = 12
if v.a < 14:
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):
if self.a < 14:
self.a = 13
self.a = 12
>>> f = F()
> def f():
> a = 12
> def g():
> global a
> if a < 14:
> return a
> print f()
> This function raises an error. Is there any way to access the a in
> f() from inside g().
Yes. Pass it to g when calling the latter and let g return the
a = 12
if parm < 14:
a = g(a)
Strange refactoring though.
BOFH excuse #400:
We are Microsoft. What you are experiencing is not a problem; it is
an undocumented feature.
As I'm struggling with this myself at the moment,
this will do the job:
a = 12
Python's scoping rules don't allow this. But you can 'box' the
value into a list and get the intended effect.
a = 
if a < 14:
a = 13
You'll get better results, in Python, by using a class instances
instead of closures. Not that there's anything wrong with Python
closures, but the scoping rules make some fun tricks too tricky.