__contains__() : Bug or Feature ???

S

sebastien.lannez

Hi everybody,

I need to overload the operator in and let him
return an object ... It seems it is not a
behavior Python expect :
.... def __contains__(self,a):
.... return 'yop'
....yop

I don't know if it's a bug or a feature but i
really need this overloading and don't know
how to do it ... Furthermore I can't use
a trick of the kind : a |in| b ... because
my overloaded operator must be called by : a in b ...

Is someone could help me ?
 
S

Stefan Behnel

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

... def __contains__(self,a):
... return 'yop'
...
True

Not sure what you're trying to achieve, but the semantics of the "in" operator
make it return a boolean value. The string "yop" evaluates to the boolean
value True, as it is not empty.

Stefan
 
C

Carsten Haese

Hi everybody,

I need to overload the operator in and let him
return an object

Why do you think you need to do that? What's the underlying problem
you're trying to solve?
 
H

Hrvoje Niksic

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top