[Python-ideas] Introduce collections.Reiterable
Stephen J. Turnbull
stephen at xemacs.org
Sat Sep 21 04:12:12 CEST 2013
Terry Reedy writes:
> Dismissing legal code as 'pathological', as more than one person has,
> does not cut it as a design principle.
But you don't even need to write a class with __getitem__() to get
that behavior.
>>> l = [11, 12, 13]
>>> for i in l:
... print(i)
... if i%2 == 0:
... l.remove(i)
...
11
12
>>> l
[11, 13]
>>>
Of course the iteration itself is probably buggy (ie, the writer
didn't mean to skip printing '13'), but in general iterables can
change themselves.
Neil himself seems to be of two minds about such cases. On the one
hand, he said the above behavior is built in to list, so it's
acceptable to him. (I think that's inconsistent: I would say the
property of being completely consumed is built in to iterator, so it
should be acceptable, too.) On the other hand, he's defined a
reiterable as a collection that when iterated produces the same
objects in the same order.
Maybe what we really want is for copy.deepcopy to do the right thing
with iterables. Then code that doesn't want to consume consumable
iterables can do a deepcopy (including replication of the closed-over
state of __next__() for iterators) before iterating.
Or perhaps the right thing is a copy.itercopy that creates a new
composite object as a shallow copy of everything except that it clones
the state of __next__() in case the object was an iterator to start
with.
More information about the Python-ideas
mailing list