False and 0 in the same dictionary
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Nov 4 18:16:06 EST 2008
Prateek <surekap at gmail.com> writes:
> >>> b = {0:'xyz', False:'abc'}
> >>> b
> {0: 'abc'} # Am I the only one who thinks this is weird?
You're not the only one; I consider this a wart in Python.
False and True should be discrete values that don't compare equal with
any other value, not even ones that evaluate to boolean False or True.
>>> False == []
False
>>> False == {}
False
>>> False == ''
False
>>> False == 0
True
This is an artifact of the fact that ‘bool’ is a subclass of ‘int’,
and that ‘False’ is implemented such that it has the same hash as ‘0’:
>>> isinstance(False, int)
True
>>> hash(False) == hash(0)
True
The above is a legacy of the original lack of a boolean type in
Python, but it's confusing and IMO unnecessary these days. It should
be enough that they all evaluate to False in a boolean context:
>>> bool([])
False
>>> bool({})
False
>>> bool('')
False
>>> bool(0)
False
PEP 285 <URL:http://www.python.org/dev/peps/pep-0285>, that introduced
the ‘bool’ type, addresses this issue:
In an ideal world, bool might be better implemented as a
separate integer type that knows how to perform mixed-mode
arithmetic. However, inheriting bool from int eases the
implementation enormously (in part since all C code that calls
PyInt_Check() will continue to work -- this returns true for
subclasses of int). Also, I believe this is right in terms of
substitutability: code that requires an int can be fed a bool
and it will behave the same as 0 or 1. Code that requires a
bool may not work when it is given an int; for example, 3 & 4
is 0, but both 3 and 4 are true when considered as truth
values.
I wonder if any of that is relevant any more.
What does backward-compatibility-is-less-important Python 3 do (I
don't have it installed)? Is there a later PEP that I've missed which
finally makes ‘bool’ a type independent from ‘int’?
--
\ “A ‘No’ uttered from deepest conviction is better and greater |
`\ than a ‘Yes’ merely uttered to please, or what is worse, to |
_o__) avoid trouble.” —Mahatma Gandhi |
Ben Finney
More information about the Python-list
mailing list