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

Rob Cliffe rob.cliffe at btinternet.com
Thu Jan 22 02:10:04 CET 2015


On 21/01/2015 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
>> ints?
>> 2) Do most Python users still agree that arithmetic operations should be
>> supported on booleans?
> 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).
May I offer a more realistic example, adapted from a real-life program:

ST1 = '20:00'
ET1 = '22:00'
ST2 = '22:00'
ET2 = '06:00'
# These variables represent times of day (24-hour clock).
# We want to check that [ST1, ET1) and [ST2, ET2) are non-empty, 
non-overlapping time periods,
# (allowing the time to wrap past midnight) as they are in this example
# (the time periods are considered to include the *S*tart *T*ime but not 
the *E*nd *T*ime).
# A naive approach might be:
if (    (ST1 <  ET1 <= ST2 <  ET2)
      or (ET2 <= ST1 <  ET1 <= ST2)
      or (ST2 <  ET2 <= ST1 <  ET1)
      or (ET1 <= ST2 <  ET2 <= ST1) ):

             <time intervals are OK>

# but this can be coded much more succinctly if at first sight less 
transparently (and sorry, Chris, without redundant parentheses :-) ) as:

if (ST1<ET1) + (ET1 <= ST2) + (ST2<ET2) + (ET2<=ST1) == 3:

             <time intervals are OK>

# Lines 1,2,3,4 in the naive approach correspond exactly
# to the cases where only the 4th/3rd/2nd/1st term, respectively,
# is False in the succinct approach.

So arithmetic on booleans may not be "pure" but it can be handy.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150122/34f49b40/attachment.html>


More information about the Python-ideas mailing list