1

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?

jsdalton
  • 6,555
  • 4
  • 40
  • 39

1 Answers1

2

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.

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Thanks, that's exactly it. I so very rarely use global variables in Python that I have yet to stumble across this. – jsdalton Mar 18 '11 at 16:37