[Python-ideas] Introduce collections.Reiterable
steve at pearwood.info
Sun Sep 22 14:21:49 CEST 2013
On Sun, Sep 22, 2013 at 08:30:43PM +1000, Nick Coghlan wrote:
> As near as I can tell, Steven's observation is that, for backwards
> compatibility reasons, iter() tolerates sequences that define __len__
> and __getitem__ without defining __iter__, whereas the collections
> ABCs require an __iter__ method for their ducktyping to trigger.
The sequence protocol doesn't require a __len__ method, it only requires
a __getitem__ method that takes consecutive ints 0, 1, 2, ... and raises
IndexError when there are no more items to get. But apart from that,
yes, that's correct. There are iterables that fail the Iterable ABC
> means that there are a small number of legacy cases where
> "isinstance(c, collections.abc.Iterable)" can be False, while calling
> "iter(c)" would still give you a working iterator.
I'm sure you realise this, but just to be clear, there's no need to
explicitly call iter(c). More to my point, you can simply iterate over c
using a for-loop:
for element in c:
thus proving that c is iterable, since you've just iterated over it.
More information about the Python-ideas