[Python-ideas] __iter__ implies __contains__?

Raymond Hettinger raymond.hettinger at gmail.com
Sun Oct 2 07:13:29 CEST 2011


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.


Raymond


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111002/db46e2b2/attachment.html>


More information about the Python-ideas mailing list