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 ?

Asked By: Moritz

||

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
Answered By: Fernando Matsumoto
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.