[Python-ideas] Should bool continue to inherit from int?

Guido van Rossum guido at python.org
Wed Jan 21 20:11:03 CET 2015


On Wed, Jan 21, 2015 at 3:32 AM, Michael Mitchell <epsilonmichael at gmail.com>
wrote:

> PEP 285 <http://legacy.python.org/dev/peps/pep-0285> provides some
> justification for why arithmetic operations should be valid on bools and
> why bool should inherit from int (see points (4) and (6) respectively).
> Since it's been 12 years (it's possible this has been brought up again
> between now and then), I thought it could be worthwhile to take another
> look.
>
> I am mostly interested in a resurveying of the questions:
> 1) Would it still be very inconvenient to implement bools separately from
> ints?
> 2) Do most Python users still agree that arithmetic operations should be
> supported on booleans?
>

It would be so massively backward compatible that it's not worth thinking
about.


> Follow-up thought:
> Something I noticed is that with PEP 484
> <https://www.python.org/dev/peps/pep-0484/> (Type Hints) specified as is,
> there would be no way to statically verify that a function will only
> operate on ints and not bools. An example would be a function that can only
> operate on integer values in a JSON dict created by the builtin `json`
> module (using the default decoder) cannot exist, as that function could
> operate on the boolean values of the dict.
>

Like Steven, I can't completely follow this thought (it looks like you were
writing too fast and jumbled a few verbs or negations) but you bring up an
interesting point: even though bools are ints, their JSON encodings are
different.

So I believe you are saying, suppose I have a function that takes an
integer argument and then JSON-encodes it and sends it to some server that
requires a JSON int. Now suppose you are adding type hints to your code,
and you add ": int" to the parameter under discussion. And now suppose you
have a faulty caller which calls this function with the argument set to
True. This program will type-check correctly, because True is a bool which
is a subclass of int, but it will run incorrectly, because (under this
assumption) True will be converted to a JSON true value, which the server
rejects.

TBH I have to think about this more. I think that in the initial version of
PEP 484 we won't try to address this (JSON without something that enforces
a schema is too dynamic to fit well into any type system), but I've opened
an issue to have a further discussion about this:
https://github.com/ambv/typehinting/issues/52

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150121/1ed74b60/attachment.html>


More information about the Python-ideas mailing list