The documentation says that __contains__
should return true if item is in self, false otherwise. However, if the method returns a non-boolean value x
, it seems that python automatically converts it to bool(x)
.
Is there any way to avoid that, and return the actual value x
? Or is this feature behavior implemented directly in the interpreter and there's no way to change this?
To get boolean true, string must contain "true". Here, case is ignored. So, "true" or "TRUE" will return boolean true. Any other string value except "true" returns boolean false.
Functions can Return a Boolean.
bool() in Python Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
A Boolean instance can have either of two values: true or false .
Note that it's not __contains__
that converts the value to a Boolean, but the in
operator that calls __contains__
. With
class Foo(list):
def __contains__(self, v):
if super().__contains__(v):
return v
else:
return False
>>> f = Foo([1,2,3])
>>> f.__contains__(2)
2
>>> 2 in f
True
A foo in bar
will be compiled to COMPARE_OP (in)
for CPython3. The implementation uses PySequence_Contain()
and then coerces to result to a bool
. So while you could return something else, you always end up with a bool after the call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With