Another dumb scope question for a closure.

Steven W. Orr steveo at syslang.net
Thu Jan 10 16:04:23 EST 2008


On Wednesday, Jan 9th 2008 at 14:01 -0000, quoth Fredrik Lundh:

=>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."

Thanks. This helps a little. But I still don't understand something. If 
it's a question of a legal reference or not, I could buy it. But what's 
really happening is that it works if it's a read-only ref but fails if 
it's a write:

>>> def inc(jj):
...     def dummy():
...             print jj
...     return dummy
... 
>>> f = inc(44)
>>> f()
44
>>> f()
44
>>> f()
44
>>> 

The problem only happens if I try to modify jj.

What am I not understanding?




More information about the Python-list mailing list