Another dumb scope question for a closure.

Mike Meyer mwm at mired.org
Wed Jan 9 15:24:03 EST 2008


On Wed, 9 Jan 2008 13:47:30 -0500 (EST) "Steven W. Orr" <steveo at syslang.net> wrote:

> So sorry because I know I'm doing something wrong.
> 
> 574 > cat c2.py
> #! /usr/local/bin/python2.4
> 
> def inc(jj):
>      def dummy():
>          jj = jj + 1
>          return jj
>      return dummy
> 
> h = inc(33)
> print 'h() = ', h()
> 575 > c2.py
> h() =
> Traceback (most recent call last):
>    File "./c2.py", line 10, in ?
>      print 'h() = ', h()
>    File "./c2.py", line 5, in dummy
>      jj = jj + 1
> UnboundLocalError: local variable 'jj' referenced before assignment
> 
> I could have sworn I was allowed to do this. How do I fix it?

Nope. This is one of the things that makes lisper's complain that
Python doesn't have "real closures": you can't rebind names outside
your own scope (except via global, which won't work here).

Using a class is the canonical way to hold state. However, any of the
standard hacks for working around binding issues work. For instance:

>>> def inc(jj):
...   def dummy():
...     box[0] = box[0] + 1
...     return box[0]
...   box = [jj]
...   return dummy
... 
>>> h = inc(33)
>>> h()
34

	<mike

-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.



More information about the Python-list mailing list