[Python-Dev] closure semantics

Samuele Pedroni pedronis at bluewin.ch
Thu Oct 23 19:08:38 EDT 2003


At 10:57 22.10.2003 -0700, Guido van Rossum wrote:

>   def tee(iterable):
>       "Return two independent iterators from a single iterable"
>       data = {}
>       cnt = 0
>       def gen(next):
>           global* cnt
>           dpop = data.pop
>           for i in count():
>               if i == cnt:
>                   item = data[i] = next()
>                   cnt += 1
>               else:
>                   item = dpop(i)
>               yield item
>       next = iter(iterable).next
>       return (gen(next), gen(next))
>
>which is IMO more readable.

it's a subtle piece of code. I wouldn't mind a more structured syntax with 
both the outer function declaring that is ok for some inner function to 
rebind some of its locals, and the inner function declaring that a local is 
coming from an outer scope:

   def tee(iterable):
       "Return two independent iterators from a single iterable"
       data = {}

       # cnt = 0 here would be ok

      share cnt = 0:  # the assignment is opt,
                       # inner functions in the suite can rebind cnt
        def gen(next):
          use cnt # OR outer cnt
         dpop = data.pop
           for i in count():
               if i == cnt:
                   item = data[i] = next()
                   cnt += 1
               else:
                   item = dpop(i)
               yield item

       # cnt = 0 here would be ok

      next = iter(iterable).next
       return (gen(next), gen(next))

yes it's heavy and unpythonic, but it makes very clear that something 
special is going on with cnt.

no time to add anything else to the thread.

regards.








    




More information about the Python-Dev mailing list