Question about nested scopes

Holger Krekel pyth at devel.trillke.net
Wed Oct 8 10:42:35 EDT 2003


Miki Tebeka wrote:
> Hello,
> 
> Can anyone explain why:
> >>> def make_inc(n):
> 	s = n
> 	def inc(i):
> 		s += i
> 		return s
> 	return inc
> 
> >>> i = make_inc(3)
> >>> i(2)
> 
> Traceback (most recent call last):
>   File "<pyshell#36>", line 1, in -toplevel-
>     i(2)
>   File "<pyshell#34>", line 4, in inc
>     s += i
> UnboundLocalError: local variable 's' referenced before assignment

you cannot change name-bindings in outer scopes.  
the compiler probably thinks because of 's+=i' that s is a 
local variable to 'inc', the inner function. but upon execution 
it notices that it is not initialized and raises the usual exception. 

However, 

> >>> 
> 
> But:
> >>> def make_inc(n):
> 	s = [n]
> 	def inc(i):
> 		s[0] += i
> 		return s[0]
> 	return inc

here you don't modify the name-binding (s references a list
all the time) but you mutate the list. 

    holger





More information about the Python-list mailing list