[Tutor] scoping rules
Karthik Gurumurthy
karthikg@aztec.soft.net
Sun, 6 Jan 2002 14:30:09 +0530
Just wanted to confirm the scoping rules.
>>> a = 1298
>>> def func(x):
a = 908
def func(x):
print "isnide func"
print "\tlocals",locals()
print "\tglobals",globals()
i =123
print "\tlocals again",locals()
a+=1 ###statement
print a
print "ok",locals()
func(87)
print a
i observed the following.
When i commented the marked statement inside the inner func,
a (908 from the enclosing function's local namespace) was present in the
inner function's local namespace.
the global a was present in the global namespace.fine.
The moment i uncomment it (ie a = a + 1), the reference to "enclosing
function's a" from locals() of
inner func was removed.
BUT, reference to a in the global namespace remained. Then why did'nt it
increment the global a?
since it is supposed to look up the locals() first and when not found search
globals()?
instead i got an unbound error.
Does it mean that moment we try to add to / manipulate a variable, python
expects the variable to
be initialized in the function's own local namespace? I mean as long as we
are "reading", it is all fine.
it worked when i put the flag global a right in the begining of the
function.
Does this mean that i will not be able to increment a (908) (defined in the
enclosing function)
inside the inner function?
hope i have framed my question properly.
thanks
karthik.