Quote:
Originally posted by rshaw
to access variables outside the local namespace you need to use the "global" keyword as in:
status = -1
def changetext():
global status
status = -status
if status ==1:
do_stuff
else:
do_other_stuff
|
Actually, you only need to use the
global keyword if you want to CHANGE variables outside the local namespace and you want those changes to stick. Observe:
Code:
>>> foo = 1
>>> def bar():
... print foo
...
>>> bar()
1
>>> def changefoo():
... foo = 2
... print foo
...
>>> changefoo()
2
>>> foo
1
>>> def reallychangefoo():
... global foo
... foo = 2
... print foo
...
>>> reallychangefoo()
2
>>> foo
2
>>>
All functions inherit the set variables of their callers, but only copies of them, not references to them. So if you modify one, it doesn't modify the variable in the caller namespace, just the local namespace ... unless you use
global.