If you're closely following the Python tag on StackOverflow, you'll notice that the same question comes up at least once a week. The question goes on like this:
Why, when run, this results in the following error:
There are a few variations on this question, with the same core hiding underneath. Here's one:
Running the statement successfully appends 5 to the list. However, substitute it for , and it raises , although at first sight it should accomplish the same.
Although this exact question is answered in Python's official FAQ (right here), I decided to write this article with the intent of giving a deeper explanation. It will start with a basic FAQ-level answer, which should satisfy one only wanting to know how to "solve the damn problem and move on". Then, I will dive deeper, looking at the formal definition of Python to understand what's going on. Finally, I'll take a look what happens behind the scenes in the implementation of CPython to cause this behavior.
The simple answer
As mentioned above, this problem is covered in the Python FAQ. For completeness, I want to explain it here as well, quoting the FAQ when necessary.
Let's take the first code snippet again:
So where does the exception come from? Quoting the FAQ:
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
But is similar to , so it should first read , perform the addition and then assign back to . As mentioned in the quote above, Python considers a variable local to , so we have a problem - a variable is read (referenced) before it's been assigned. Python raises the exception in this case .
So what do we do about this? The solution is very simple - Python has the global statement just for this purpose:
This prints , without any errors. The statement tells Python that inside , refers to the global variable , even if it's assigned in .
Actually, there is another variation on the question, for which the answer is a bit different. Consider this code:
This kind of code may come up if you're into closures and other techniques that use Python's lexical scoping rules. The error this generates is the familiar . However, applying the "global fix":
Doesn't help - another error is generated: . Python is right here - after all, there's no global variable named , there's only an in . It may be not local to , but it's not global. So what can you do in this situation? If you're using Python 3, you have the keyword. Replacing by in the last snippet makes everything work as expected. is a new statement in Python 3, and there is no equivalent in Python 2 .
The formal answer
Assignments in Python are used to bind names to values and to modify attributes or items of mutable objects. I could find two places in the Python (2.x) documentation where it's defined how an assignment to a local variable works.
One is section 6.2 "Assignment statements" in the Simple Statements chapter of the language reference:
Assignment of an object to a single target is recursively defined as follows. If the target is an identifier (name):
- If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace.
- Otherwise: the name is bound to the object in the current global namespace.
Another is section 4.1 "Naming and binding" of the Execution model chapter:
If a name is bound in a block, it is a local variable of that block.
When a name is used in a code block, it is resolved using the nearest enclosing scope. [...] If the name refers to a local variable that has not been bound, a UnboundLocalError exception is raised.
This is all clear, but still, another small doubt remains. All these rules apply to assignments of the form which clearly bind to . But the code snippets we're having a problem with here have the assignment. Shouldn't that just modify the bound value, without re-binding it?
Well, no. and its cousins (, , etc.) are what Python calls "augmented assignment statements" [emphasis mine]:
An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.
An augmented assignment expression like can be rewritten as to achieve a similar, but not exactly equal effect. In the augmented version, is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.
With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.
So when earlier I said that is similar to, I wasn't telling all the truth, but it was accurate with respect to binding. Apart for possible optimization, counts exactly as when binding is considered. If you think carefully about it, it's unavoidable, because some types Python works with are immutable. Consider strings, for example:
The first line binds to the value "abc". The second line doesn't modify the value "abc" to be "abcdef". Strings are immutable in Python. Rather, it creates the new value "abcdef" somewhere in memory, and re-binds to it. This can be seen clearly when examining the object ID for before and after the :
Note that some types in Python are mutable. For example, lists can actually be modified in-place:
didn't change after , because the object referenced was just modified. Still, Python re-bound to the same object .
The "too much information" answer
This section is of interest only to those curious about the implementation internals of Python itself.
One of the stages in the compilation of Python into bytecode is building the symbol table . An important goal of building the symbol table is for Python to be able to mark the scope of variables it encounters - which variables are local to functions, which are global, which are free (lexically bound) and so on.
When the symbol table code sees a variable is assigned in a function, it marks it as local. Note that it doesn't matter if the assignment was done before usage, after usage, or maybe not actually executed due to a condition in code like this:
We can use the module to examine the symbol table information gathered on some Python code during compilation:
So we see that was marked as local in . Marking variables as local turns out to be important for optimization in the bytecode, since the compiler can generate a special instruction for it that's very fast to execute. There's an excellent article here explaining this topic in depth; I'll just focus on the outcome.
The function in handles variable name references. To generate the correct opcode, it queries the symbol table function . For our , this returns a bitfield with in it. Having seen , generates a . We can see this in the disassembly of :
The first block of instructions shows what was compiled to. You will note that already here (before it's actually assigned), is used to retrieve the value of .
This is the instruction that will cause the exception to be raised at runtime, because it is actually executed before any is done for . The gory details are in the bytecode interpreter code in :
Ignoring the macro-fu for the moment, what this basically says is that once is seen, the value of is obtained from an indexed array of objects . If no was done before, this value is still , the branch is not taken  and the exception is raised.
You may wonder why Python waits until runtime to raise this exception, instead of detecting it in the compiler. The reason is this code:
Suppose is a function that returns , possibly due to some user input. In this case, binds locally, so the reference to it in is no longer unbound. This code will then run without exceptions. Of course if actually turns out to return , the exception will be raised. Python has no way to resolve this at compile time, so the error detection is postponed to runtime.
Previous Chapter: Namespaces
Next Chapter: File Management
Global and Local Variables
Global and local Variables in Functions
Let's have a look at the following function:def f(): print s s = "I hate spam" f() The variable s is defined as the string "I hate spam", before we call the function f(). The only statement in f() is the "print s" statement. As there is no local s, the value from the global s will be used. So the output will be the string "I hate spam". The question is, what will happen, if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code: def f(): s = "Me too." print s s = "I hate spam." f() print s The output looks like this: Me too. I hate spam. What if we combine the first example with the second one, i.e. first access s and then assigning a value to it? It will throw an error, as we can see in the following example: def f(): print s s = "Me too." print s s = "I hate spam." f() print s If we execute the previous script, we get the error message: UnboundLocalError: local variable 's' referenced before assignment Python "assumes" that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword "global", as can be seen in the following example: def f(): global s print s s = "That's clear." print s s = "Python is great!" f() print s Now there is no ambiguity. The output is as follows: Python is great! That's clear. That's clear. Local variables of functions can't be accessed from outside, when the function call has finished: def f(): s = "I am globally not known" print s f() print s If you start this script, you get an output with the following error message: I am globally not known Traceback (most recent call last): File "global_local3.py", line 6, in <module> print s NameError: name 's' is not defined The following example shows a deliberate combination of local and global variables and function parameters: def foo(x, y): global a a = 42 x,y = y,x b = 33 b = 17 c = 100 print a,b,x,y a,b,x,y = 1,15,3,4 foo(17,4) print a,b,x,y The output of the script above looks like this: 42 17 4 17 42 15 3 4
Previous Chapter: Namespaces
Next Chapter: File Management