Question about nested scopes

Miki Tebeka tebeka at cs.bgu.ac.il
Wed Oct 8 10:13:58 EDT 2003


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
>>> 

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

>>> i = make_inc(2)
>>> i(2)
4
>>> i(2)
6

Thanks.
Miki




More information about the Python-list mailing list