0 equals False, was Re: (unknown)

Peter Otten __peter__ at web.de
Wed Mar 23 04:51:34 EDT 2016


Nick Eubank wrote:

> Hello All,
> 
> 
> Found an odd behavior I'd never known about today, not sure if it's a bug
> or known. Python 3.4.4 (anaconda).

This is a feature. Old versions of Python did not have True and False, so 
they were added in a compatible way.

> True, False, 0, 1 can all be used as dictionary keys.
> 
> But Apparently True and 1 hash to the same item and False and 0 hash to
> the same item, so they can easily overwrite (which I spent a while banging
> my head over today).
> 
> In other words:
> 
>  In[1]:
>      d = {True: 'a', False: 'b'}
>      d[0] = 'z'
>      d[False]
> 
> Out[1]:
>      'z'
> 
> I understand that True and False are sub-types of ints, but it's not clear
> to me why (i.e. certainly didn't feel intuitive) that they would be
> treated the same as keys.
> 
> Relatedly, if this is a desired behavior, any advice one how best to work
> with dictionaries when one wants "True" and 1 to be different? I'm working
> on a function that accepts arguments that may be "True" or 1 (meaning very
> different things) and am seeking a pythonic solution...

The pythonic solution is "don't do this". The == operator cannot 
discriminate between 0, 0.0, and False, or 1, 1.0, and True. 

True and False are singletons, so you can check identity with

x is True or x is False

A type check will also work: 

type(x) == bool
isinstance(x, bool) # bool cannot be subclassed

If you provide some context we may be able to come up with an alternative 
approach that fits your use case.




More information about the Python-list mailing list