I looking some explanations with Namespace concept in functions.
Here is a code which will raise UnboundLocalError: local variable … referenced before assignment
x = 1
def foo():
print x
x = 2
I Understand this should raise exception. But I want to understand how python know that is variable is in local namespace. At line print x, x is not in local variable dict.
x = 1
def foo():
print 'local before print x : ',locals()
print x
print 'local after print x :',locals()
x = 2
foo() # call function, print local namespace before raising exception
local before print x : {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
UnboundLocalError: local variable 'x' referenced before assignment
Before print x, local namespace dict is empty {}(which is very obvious). So how does python know that x is local variable.
This works differently with classes
a = [1]
class b():
c = a
a = 2
print 'c inside class ', b.c
'c inside class [1]'
d = b()
No Exception is raised with similar case in class.
If someone can help me explaining concept, how python knows before assignment that this variable is local variable.
I have checked many forms and sites for explanation but didn't find any.
There are post and forms which explain how to solve this case. example. UnboundLocalError: local variable … referenced before assignment . But I am looking for python working behind.