"0 in [True,False]" returns True

Antoon Pardon apardon at forel.vub.ac.be
Tue Dec 13 02:55:17 EST 2005


Op 2005-12-12, Fredrik Lundh schreef <fredrik at pythonware.com>:
> Pierre Quentel wrote:
>
>> In some program I was testing if a variable was a boolean, with this
>> test : if v in [True,False]
>>
>> My script didn't work in some cases and I eventually found that for v =
>> 0 the test returned True
>>
>> So I changed my test for the obvious "if type(v) is bool", but I still
>> find it confusing that "0 in [True,False]" returns True
>>
>> By the way, I searched in the documentation what "obj in list" meant and
>> couldn't find a precise definition (does it test for equality or
>> identity with one of the values in list ? equality, it seems) ; did I
>> miss something ?
>
>>>> issubclass(bool, int)
> True
>>>> isinstance(False, int)
> True
>>>> False == 0
> True
>>>> int(False)
> 0
>
> but seriously, unless you're writing an introspection tool, testing for
> bool is pretty silly.  just use "if v" or "if not v", and leave the rest to
> Python.

That depends on the circumstances. I have code where a particular
variable can be a boolean or an integer. I don't want that code
to behave the same on 0 and False nor on any other number and
True.

-- 
Antoon Pardon



More information about the Python-list mailing list