[Python-3000] Parallel iteration syntax

Ian Bicking ianb at colorstudy.com
Tue Mar 28 21:07:31 CEST 2006


Ian Bicking wrote:
> Guido van Rossum wrote:
> 
>>The proposed syntax doesn't quite jive with my guts, and the issue of
>>"what to do if they are of unequal length" is a good one, which is
>>better solved by being explicit and using zip (== izip).
> 
> 
> Is zip() going to be equivalent to izip(), or will it be a view?  I vote 
> for view.  xrange() does not produce an iterator, so there is some 
> precedence that we not replace list-constructing-builtins with 
> iterator-constructing-builtins.

It occurs to me it could just be a funny kind of delegate as well:

class zip:
     def __init__(self, *subobjs):
         self._subobjs = subobjs
     def __repr__(self):
         return '%s(%s)' % (
             self.__class__.__name__,
             ', '.join(repr(obj) for obj in self._subobjs))
     def __getattr__(self, attr):
         def repl(*args, **kw):
             return tuple([getattr(obj, attr)(*args, **kw)
                           for obj in self._subobjs])
         return repl
     def __iter__(self):
         iters = [iter(obj) for obj in self._subobjs]
         while 1:
             yield tuple([i.next() for i in iters])

z = zip([1, 2, 3], ['one', 'two', 'three'])


That __getattr__ doesn't work correctly for new style classes.  I 
haven't figured out the proper way to create delegates since new-style 
classes came along.

Also, maybe zip() really should be sequence-oriented.  E.g., z[0:2] 
should probably return [(1, 'one'), (2, 'two')], not ([1, 2], ['one', 
'two']) (as it does with this implementation).  So maybe it's not quite 
so generalizable as I make it here.  But a more specific sequence-based 
delegation seems appropriate.

z[0] should (and does) only work if all inputs are indexable; iterators 
as input are fine, so long as you only use the resulting object as an 
iterator.  That is, you get the least-common-denominator of the inputs. 
  I think this is attractive since it preserves the current behavior of 
zip() in many (but not all) ways, and seems both fairly transparent and 
efficient.

The resulting object could be mutable -- there's no technical reason it 
should be mutable -- but it is somewhat questionable.

-- 
Ian Bicking  /  ianb at colorstudy.com  /  http://blog.ianbicking.org


More information about the Python-3000 mailing list