For loop extended syntax

George Sakkis gsakkis at rutgers.edu
Sun Mar 20 16:22:58 EST 2005


"Heiko Wundram" <modelnine at ceosg.de> wrote in message
news:mailman.649.1111349408.1799.python-list at python.org...
>
> On Sunday 20 March 2005 20:47, George Sakkis wrote:
> > Not always. Say for example that you're doing some 2D geometry stuff, and
> > later you have to extend it to 3D. In this case you may have to deal with
> > both 2D and 3D objects, and map the former to the latter when necessary.
>
> But this rather sounds like you'd want an adaptor iterator, like the
> following:
>
> >>> class AdaptPossible2D(object):
> ...   def __init__(self,data):
> ...     self.data = data
> ...   def __iter__(self):
> ...     for item in self.data:
> ...       if len(item) == 2:
> ...         yield item+(0,)
> ...       else:
> ...         yield item
> ...
> >>> for x,y,z in AdaptPossible2D([(1,2),(1,2,3),(3,4)]):
> ...   print x,y,z
> ...
> 1 2 0
> 1 2 3
> 3 4 0
>
> Using the above code makes it absolutely clear what you want, and doesn't need
> any new syntax which can be ambiguous like (x=0,y,z=0), etc. The above idiom
> also takes only constant extra space, as it doesn't duplicate the list during
> iteration.


Once more, the 2D/3D example was just that, an example; my point was not to find a specific solution
to a specific problem. Extending the "for .. in" syntax would be an elegant way to express this idea
in a more succint, familiar and generic way than a customized adaptor. As for the ambiguity, it is
not more ambiguous than function signatures as long as all keyword arguments go after all the
required ones; I'm not suggesting that (x=0,y,z=0) should be valid.

George





More information about the Python-list mailing list