[Python-ideas] Introduce collections.Reiterable

Stephen J. Turnbull stephen at xemacs.org
Fri Sep 20 19:34:58 CEST 2013

Andrew Barnert writes:

 > And that makes me think that I (and the people who have been
 > responding to you before me) have missed something important in
 > this "manually iterable" or "directly iterable" idea. So, maybe you
 > should try explaining it a different way?

How about "'Iterable' is a terrible name for an ABC that excludes an
important class of iterables"?

You see, the library manual lies (section 4.5 "Iterator types"):

    One method needs to be defined for container objects to provide
    iteration support:


But in fact this is contradicted (section 2 "Built-in functions"):

    iter(object[, sentinel])
        Return an iterator object. The first argument is interpreted very
        differently depending on the presence of the second argument. Without
        a second argument, object must be a collection object which supports
        the iteration protocol (the __iter__() method), or it must support the
        sequence protocol (the __getitem__() method with integer arguments
        starting at 0).

I suggest that section 4.5 be corrected to

    Container objects provide iteration support when either of the methods

    container.__iter__()            # iteration protocol
    container.__getitem__()         # sequence protocol

    is defined.  In the latter case, __getitem__() must accept integer
    arguments starting at 0.

Curiously, all of the built-in sequences support both protocols.  I
suppose this section ought to say which is preferred.

The net result is that I guess Nick's test needs to be refined to

    def isIterable(o):
            return True
        except TypeError:
            return False

    def isReiterable(o):
        return isIterable and not isinstance(o, collections.abc.Iterator)

More information about the Python-ideas mailing list