__contains__() : Bug or Feature ???

Hrvoje Niksic hniksic at xemacs.org
Fri Sep 21 15:37:33 CEST 2007

"sebastien.lannez at gmail.com" <sebastien.lannez at gmail.com> writes:

> I need to overload the operator in and let him return an object
> ... It seems it is not a behavior Python expect :

Python expects it all right, but it intentionally converts the value
to a boolean.  The 'in' operator calls PySequence_Contains, which
returns a boolean value at the C level.  User-supplied __contains__ is
implemented as an adaptor in typeobject.c (slot_sq_contains).  It
takes the value returned by your __contains__ implementation and
converts it to 0 or 1.

I don't think you can overload 'in' as you want without pervasive
changes to CPython source code.

More information about the Python-list mailing list