[Python-ideas] __iter__ implies __contains__?

Antoine Pitrou solipsis at pitrou.net
Sat Oct 1 20:33:35 CEST 2011


On Sat, 1 Oct 2011 20:27:03 +0200
Masklinn <masklinn at masklinn.net> wrote:
> On 2011-10-01, at 20:13 , Antoine Pitrou wrote:
> > Hello,
> > 
> > I honestly didn't know we exposed such semantics, and I'm wondering if
> > the functionality is worth the astonishement:
> > 
> >>>> "abc" in io.StringIO("abc\ndef\n")
> > False
> >>>> "abc\n" in io.StringIO("abc\ndef\n")
> > True
> > 
> > Basically, io.StringIO provides iteration (it yields lines of text) and
> > containment is apparently inferred from that.
> There's a second fallback: Python will also try to iterate using
> __getitem__ and integer indexes __iter__ is not defined.
> 
> The resolution is defined in the expressions doc[0]:
> 
> > For user-defined classes which define the __contains__() method, x in
> > y is true if and only if y.__contains__(x) is true.
> >
> > For user-defined classes which do not define __contains__() but do
> > define __iter__(), x in y is true if some value z with x == z is
> > produced while iterating over y. If an exception is raised during the
> > iteration, it is as if in raised that exception.

Ah, thanks for the pointer.
I think we should add a custom IOBase.__contains__ raising a TypeError,
then. The current semantics don't match what most people would expect
from a "file containment" predicate.

Regards

Antoine.





More information about the Python-ideas mailing list