Python: namespaces, error: local variable 'b' referenced before assignment
Question:
This code works as expected:
def my_fun():
a = b
a = 5
print a
b = 2
my_fun()
print b
And I get:
5
2
But if I do:
def my_fun():
a = b
a = 5
b = 1
print a
b = 2
my_fun()
print b
I do get the error: UnboundLocalError: local variable 'b' referenced before assignment
What happens here ? Although b
is visible to the function, I cannot change it inside the function ?
Answers:
When you assign b = 1
, the interpreter starts treating b
as a local variable. If you want to assign the global variable b
, you have to put the statement global b
at the start of your function.
def my_fun():
global b
# do stuff
b = 2
my_fun()
print b
This code works as expected:
def my_fun():
a = b
a = 5
print a
b = 2
my_fun()
print b
And I get:
5
2
But if I do:
def my_fun():
a = b
a = 5
b = 1
print a
b = 2
my_fun()
print b
I do get the error: UnboundLocalError: local variable 'b' referenced before assignment
What happens here ? Although b
is visible to the function, I cannot change it inside the function ?
When you assign b = 1
, the interpreter starts treating b
as a local variable. If you want to assign the global variable b
, you have to put the statement global b
at the start of your function.
def my_fun():
global b
# do stuff
b = 2
my_fun()
print b