"0 in [True,False]" returns True

Fredrik Lundh fredrik at pythonware.com
Mon Dec 12 16:36:03 EST 2005


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.

</F>






More information about the Python-list mailing list