On 6/5/2016 2:37 PM, Giampaolo Rodola' wrote:
On Sun, Jun 5, 2016 at 7:23 PM, Steven D'Aprano <steve@pearwood.info <mailto:steve@pearwood.info>> wrote:
On Sun, Jun 05, 2016 at 06:37:48PM +0200, Giampaolo Rodola' wrote: > >>> 1 + True > 2 > >>> 1 + False > 1 > >>> > > I bumped into this today by accident and I can't recall ever being aware of > this. Why isn't this a TypeError in Python 3?
Because bool is a subclass of int, and has been since it was first introduced back in Python 2.2. I'm not quite sure what your question is about... are you asking what was the original justification for making True and False equal to 1 and 0? If so, see the PEP:
https://www.python.org/dev/peps/pep-0285/
Or do you mean to ask why it wasn't changed in Python 3? Well, changed to what? All the reasons given in the PEP still hold, and there's no really compelling reason to make bool something else. Since bools aren't broken, why change them?
I've read through the PEP and I understand the rationale about why True/False is a subclass of int
'subclass of int' means 'instances are ints'
What I find odd though is that a bool can be used in arithmetical operations as if it was the exact same thing as a number.
That is what subclass means.
I mean, to me this is just odd:
1 + True 2
I would have expected that to be treated the same as:
1 + "1" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
This would only be sensible if Bools were strings.
On the other hand (and I'm gonna contradict myself with what I've just said above) on chapter 4: / / / There's a small but vocal minority that would prefer to see/ / "textbook" bools that don't support arithmetic operations at/ / all, but most reviewers agree with me that bools should always/ / allow arithmetic operations./
...so maybe supporting arithmetical operations was also a primary intention,
For some people, yes.
in which case my question is "why?".
Just a few days ago, I read someone, while discussing an fairly large application, saying how nice python is because it allows simple code like score = sum(s==c for s, c in zip(student, correct)) (This is not the code from the application, but close enough.) There is real code in the wild exploiting issubclass(bool, int), which could be broken if that were changed. -- Terry Jan Reedy