The following code prints 123:
>>> a = 123
>>> def f():
... print a
...
>>> f()
123
>>>
But the following fails:
>>> a = 123
>>> def f():
... print a
... a = 456
... print a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>>
I would have expected this to print:
123
456
What am I missing here?
P.S. I’m using Python 2.6.6 if that matters.
If a function only reads from a variable, it’s assumed to be global. If the function writes to it ever, it’s assumed to be local. In your second function, a is written to, so it’s assumed to be local. Then the line above (where it’s read from) isn’t valid.
Here’s a link to the Python FAQ: http://docs.python.org/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python