[Python-ideas] __iter__ implies __contains__?
Greg Ewing
greg.ewing at canterbury.ac.nz
Mon Oct 3 00:00:46 CEST 2011
Masklinn wrote:
> since Python calls the exact same method, if you somehow do a
> containment check (or an iteration) of a simple k:v collection
> instead of getting a clear exception about a missing `__iter__`
> or `__contains__` you get a not-very-informative `KeyError: 0`
> 3 or 4 levels down the stack, and now have to hunt how in hell's
> name somebody managed to call `collection[0]`.
Iterators are best thought of as temporary, short-lived
objects that you create when you need them and use them
while they're fresh. Passing an iterator to something that
is not explicitly documented as being designed for an
iterator, as opposed to an iterable, is asking for trouble.
It was probably a mistake not to make a clearer distinction
between iterables and iterators back when the iterator
protocol was designed, but we're stuck with it now.
Note that this kind of problem is less likely to occur
in Py3, because methods such as dict.keys() and dict.items()
now return iterable views rather than iterators, so you
can iterate over them multiple times without any trouble.
I think this is also a good design pattern to follow when
creating your own iteration-capable objects. In other
words, don't write methods that return iterators directly;
instead, return another object with an __iter__ method.
--
Greg
More information about the Python-ideas
mailing list