[Python-ideas] Should bool continue to inherit from int?
python at mrabarnett.plus.com
Wed Jan 21 19:12:13 CET 2015
On 2015-01-21 13:27, Chris Angelico wrote:
> On Wed, Jan 21, 2015 at 10:32 PM, Michael Mitchell
> <epsilonmichael at gmail.com> wrote:
>> PEP 285 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
>> 2) Do most Python users still agree that arithmetic operations should be
>> supported on booleans?
> We recently had a thread on python-list about this. There are a number
> of useful operations that can be done on bools-as-integers (such as
> summing them to quickly and efficiently figure out how many are True).
> But let me rephrase your question:
> "Python's booleans currently support arithmetic operations. Should we
> no longer support them?"
> Even leaving aside the massive backward compatibility implications
> (which would probably mean this kind of removal can't be done until
> Python 4.0 or 5.0 or who-knows-when), the philosophical question of
> "why should we NOT support something" needs a strongly-justified
> answer. Sure, it might make sense to have a non-integer type for the
> two special objects True and False; but what would the language gain
> by it?
> It's quite common for 1 and 0 to *be* the language's True and False
> values. REXX has no types, but in a boolean context, any value other
> than 1 or 0 triggers an error; C doesn't have a boolean type, and
> comparisons return 1 or 0; C++ has a boolean type, but will cheerfully
> and silently up-cast it to integer if you do arithmetic on it; Pike
> uses 1 and 0 (parallel to C), and allows any object to declare its own
> "truthiness" (more-or-less equivalently to Python's __bool__ method).
> All of them allow you to write stuff like:
> if (((1==1) + (1==0) + (0==0)) == 2)
> which will be true (if a little over-parenthesized for some people's
> liking). These kinds of constructs allow you to do fuzzy matching
> fairly efficiently - imagine the three conditions are three different
> search criteria, and instead of simply seeing if the sum is 2, you
> sort a large number of results by that sum. The more conditions match,
> the greater the sum. Sure, this isn't a *common* requirement, but what
> would the language really gain by forcing you to intify with something
> like "lambda b: 1 if b else 0"?
Pascal has 'ord' for getting the ordinal number from an enumerated
type, so perhaps that could be used:
ord(False) == 0
ord(True) == 1
Currently it's just the inverse of 'chr'.
More information about the Python-ideas