1 It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.
2
3 This code:
4
5 >>>
6 >>> x = 10
7 >>> def bar():
8 ... print x
9 >>> bar()
10 10
11 works, but this code:
12
13 >>>
14 >>> x = 10
15 >>> def foo():
16 ... print x
17 ... x += 1
18 results in an UnboundLocalError:
19
20 >>>
21 >>> foo()
22 Traceback (most recent call last):
23 ...
24 UnboundLocalError: local variable 'x' referenced before assignment
25 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. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized local variable and an error results.
26
27 In the example above you can access the outer scope variable by declaring it global:
28
29 >>>
30 >>> x = 10
31 >>> def foobar():
32 ... global x
33 ... print x
34 ... x += 1
35 >>> foobar()
36 10
37 This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
38
39 >>>
40 >>> print x
41 11