Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105527
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | 0 equals False, was Re: (unknown) |
| Date | 2016-03-23 09:51 +0100 |
| Organization | None |
| Message-ID | <mailman.40.1458723109.2244.python-list@python.org> (permalink) |
| References | <CAFWQgO=o-rPavakLZZBRxAthM5g7xE=Mn4hwcFPxTUvCEXn7SQ@mail.gmail.com> |
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.
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
0 equals False, was Re: (unknown) Peter Otten <__peter__@web.de> - 2016-03-23 09:51 +0100 Re: 0 equals False, was Re: (unknown) gst <g.starck@gmail.com> - 2016-03-23 08:03 -0700
csiph-web