confusing UnboundLocalError behaive

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Feb 23 03:47:13 EST 2009


En Mon, 23 Feb 2009 06:06:58 -0200, neoedmund <neoedmund at gmail.com>  
escribió:

> it seems "you cannot change the outter scope values but can use it
> readonly."

Exactly.
Python doesn't have variable "declarations" - so the compiler uses this  
rule: "if the variable is assigned to, anywhere in the function body, it's  
local". This is done by static analysis when the code is compiled.

> 2.
> def test():
> 	abc="111"
> 	def m1():
> 		print(abc)
> 		abc+="222"
> 	m1()
> test()
>
> Output:
>    print(abc)
> UnboundLocalError: local variable 'abc' referenced before assignment

abc is assigned to, so it is local (and different from the abc in its  
enclosing scope). You can't print abc until it is assigned "something".

> 3.
> def test2():
> 	abc=[111]
> 	def m1():
> 		print(abc)
> 		abc.append(222)
> 	m1()
> 	print(abc)

No assignment to abc, so it's not local; print(abc) starts looking for it  
in all the enclosing scopes (up to the module global scope, and last, the  
builtin module).

-- 
Gabriel Genellina




More information about the Python-list mailing list