nested functions - access to variables?
Andrew Koenig
ark at research.att.com
Wed Feb 26 11:55:53 EST 2003
Oleg> suppose we have a program like this one:
Oleg> g = 100
Oleg> def a():
Oleg> g = 200
Oleg> def b():
Oleg> global g
Oleg> g = 300
Oleg> b()
Oleg> print g
Oleg> a()
Oleg> print g
Oleg> this thing prints 200 300, while i really need it to print 300 100.
Oleg> When I remove 'global g', it prints 200 100, as one should expect.
...
Oleg> So the question is, how to access function's variables from its
Oleg> nested function? Python version is 2.2.
A function cannot affect the name binding in its surrounding context,
unless that context is global. So there is no way for b() to change
the binding of the variable g defined in a().
However, a function *can* change the value of the object to which
a name in the surrounding context is bound, as long as it remains
the same object. Which means that you can do this:
g = 100
def a():
g = [200]
def b():
g[:] = [300]
b()
print g
a()
print g
and it will print [300] followed by 100.
--
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
More information about the Python-list
mailing list