[Python-ideas] __iter__ implies __contains__?

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Oct 3 09:22:14 CEST 2011


Guido van Rossum wrote:

> And I can assure you that this was no coincidence, mistake or
> accident. It was done very deliberately.

I know, and I understand why it seemed like a good idea at
the time. It's just that my own experiences since then have
led me to think that a different choice might have worked
out better.

Consuming an iterator is something you really don't want to
do accidentally, just like you don't want to accidentally
do anything else that changes the internal state of an
object. The current design makes it all too easy to do
just that.

Passing non-reiterable objects around is not something that
I think should be encouraged. Ideally, one would hardly ever
see a bare iterator -- they should be like virtual particles,
coming into existence when needed, performing their function
and then disappearing before anyone notices they're there.

I think Py3 is heading in the right direction with things
like dict.keys() returning iterable views instead of iterators.
Generally, we should strive to make reiterables easier to
obtain and non-reiterables harder to obtain.

Maybe when we've been doing that for long enough, we'll be
in a position to make fallback to iteration work only for
reiterables without breaking too much code.

-- 
Greg



More information about the Python-ideas mailing list