Another dumb scope question for a closure.

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 20:01:24 CET 2008


Steven W. Orr 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

http://docs.python.org/ref/naming.html has the answer:

     "If a name binding operation occurs anywhere within a code block,
     all uses of the name within the block are treated as references
     to the current block."

> I could have sworn I was allowed to do this. How do I fix it?

use a class to hold state, like everyone else does?

</F>




More information about the Python-list mailing list