Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for `__contains__` to return non-boolean value?

Tags:

python

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?

like image 984
blue_note Avatar asked Nov 17 '18 13:11

blue_note


People also ask

Can a string return a Boolean?

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.

Can function return Boolean?

Functions can Return a Boolean.

Which method is used to return or convert a value to a Boolean value?

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.

What value will Boolean return?

A Boolean instance can have either of two values: true or false .


2 Answers

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
like image 160
chepner Avatar answered Sep 21 '22 17:09

chepner


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.

like image 41
user2722968 Avatar answered Sep 22 '22 17:09

user2722968