jsdalton
jsdalton

Reputation: 6825

Setting the value of a global variable in the context of a function raises UnboundLocalError?

Maybe my coffee is not strong enough this morning, but this behavior is confusing me right now:

>>> a = 'foo'
>>> def func1():
...   print a
... 
>>> def func2():
...   print a
...   a = 'bar'
... 
>>> func1()
foo
>>> func2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func2
UnboundLocalError: local variable 'a' referenced before assignment

(Note that it's the print a statement that's raising the error in func2(), not a = 'bar'.)

Can somebody explain to me what's going on here?

Upvotes: 1

Views: 1290

Answers (1)

Fred Foo
Fred Foo

Reputation: 363637

Because a is being set inside func2, Python assumes it's a local variable. Put a global a declaration before the print statement:

def func2():
    global a
    print a
    a = 'bar'

See also this question about Python scoping rules.

Upvotes: 2

Related Questions