Another dumb scope question for a closure.

Waldemar Osuch waldemar.osuch at gmail.com
Wed Jan 9 17:52:09 EST 2008


On Jan 9, 11:47 am, "Steven W. Orr" <ste... 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?
>

I have seen this approach on ActiveState Cookbook but can not find a
reference to it right now.

>>> def inc(jj):
...     def dummy():
...         dummy.jj += 1
...         return dummy.jj
...     dummy.jj = jj
...     return dummy
...
>>> h = inc(33)
>>> h()
34
>>> h()
35
>>> i = inc(12)
>>> i()
13
>>> i()
14

Waldemar



More information about the Python-list mailing list