confusing UnboundLocalError behaive

neoedmund neoedmund at gmail.com
Mon Feb 23 03:06:58 EST 2009


see the 3 small piece of code, i cannot understand why it result as
this.

1.
def test():
	abc="111"
	def m1():
		print(abc)
	m1()
test()

Output: 111

2.
def test():
	abc="111"
	def m1():
		print(abc)
		abc+="222"
	m1()
test()

Output:
   print(abc)
UnboundLocalError: local variable 'abc' referenced before assignment

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

Output:
[111]
[111,222]

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



More information about the Python-list mailing list