"0 in [True,False]" returns True

bonono at gmail.com bonono at gmail.com
Mon Dec 12 22:17:59 EST 2005


Fredrik Lundh wrote:
> 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.
>
The OP's code(and his work around) doesn't look like he is testing for
boolean but more like the data type of something. I thought there is
some idiom in python which said something like "don't assume" ?




More information about the Python-list mailing list