Comment on PEP-0322: Reverse Iteration Methods

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Sun Sep 28 23:53:31 EDT 2003


On Thu, 25 Sep 2003 00:58:45 GMT, "Raymond Hettinger"
<vze4rx4y at verizon.net> wrote:

>Please comment on the new PEP for reverse iteration methods.
>Basically, the idea looks like this:

I have one last suggestion to make on this. Instead of adding a method
to the container, possibly it should be added to the iterator.

If the iterator class was roughly equivalent to the following...

  class Iter (object) :
    def __init__ (self, p_Src) :
      "Keep ref to container to iterate, plus other setup stuff."
      self.Src = p_Src
      ...

    def __iter__ (self) :
      "Allow iterator to behave as iterable for convenience"
      return self

    def reverse (self) :
      "Set reverse-order iteration mode"
      ...
      return self

    def next (self) :
      "Get next item"
      ...

We could write...

  for i in iter (seq).reverse () :

Possible advantages being...

1.  The need for/existence of an iterator is made explicit by the
    already familiar 'iter' call.

2.  Because the 'reverse' method is applied to the iterator rather
    than the container, the existing spelling can be used without
    worries about iterating over strings (or user classes) that
    already have a 'reverse' method.

3.  It's an extensible approach (other 'iterator modifiers' could be
    defined in much the same way, e.g. range restriction) yet at the
    same time both simple and lightweight.

The xrange and enumerate classes would probably also adopt the
'reverse' spelling for consistency...

  for i in xrange(10).reverse() :
    ...


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list