[Tutor] python closures

Eike Welk eike.welk at gmx.net
Mon Nov 30 18:36:52 CET 2009

On Monday 30 November 2009, Hugo Arts wrote:
> Consider this python session:
>  >>> x = 0
>  >>> def f():
> 		x = x + 1
>  >>> f()
> Traceback (most recent call last):
>   File "<pyshell#27>", line 1, in <module>
>     f()
>   File "<pyshell#26>", line 2, in f
>     x = x + 1
> UnboundLocalError: local variable 'x' referenced before assignment
Ah... what a pity I didn't try this. I used similar code in my 
response to Spir and thought it would be somehow connected to 
closures. Sending nonsense statements to the list again... 

> The python docs offers some insight:
> The execution of a function introduces a new symbol table used for
> the local variables of the function. More precisely, all variable
> assignments in a function store the value in the local symbol
> table; whereas variable references first look in the local symbol
> table, then in the local symbol tables of enclosing functions, then
> in the global symbol table, and finally in the table of built-in
> names. Thus, global variables cannot be directly assigned a value
> within a function (unless named in a global statement), although
> they may be referenced.
> ( from
> http://docs.python.org/tutorial/controlflow.html#defining-functions
> )
> In short, the problem is that writing "x =" will create a new
> (unbound) local name for x, hiding the global one. The following
> reference to x will find the local unbound variable and start
> complaining.
I find that behavior quite counterintuitive. I expect:
1. 'x' is looked up, global variable 'x' is found; 
2. the addition is performed; 
3. a local name 'x' is created and bound to the result of the 

Producing the error is not insane. Because referencing a global 
variable and shadowing it in the same statement is bad style. 


More information about the Tutor mailing list