[Python-ideas] __iter__ implies __contains__?

Guido van Rossum guido at python.org
Sun Oct 2 19:05:50 CEST 2011


On Sat, Oct 1, 2011 at 10:13 PM, Raymond Hettinger
<raymond.hettinger at gmail.com> wrote:
>
> On Oct 1, 2011, at 2:13 PM, Antoine Pitrou wrote:
>
> I honestly didn't know we exposed such semantics, and I'm wondering if
> the functionality is worth the astonishement:
>
> Since both __iter__ and __contains__ are deeply tied to "in-ness",
> it isn't really astonishing that they are related.
> For many classes, if "any(elem==obj for obj in s)" is True,
> then "elem in s" will also be True.
> Conversely, it isn't unreasonable to expect this code to succeed:
>    for elem in s:
>          assert elem in s
> The decision to make __contains__ work whenever __iter__ is defined
> probably goes back to Py2.2.   That seems to have worked out well
> for most users, so I don't see a reason to change that now.

+1

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list