bool and int

Ben Bacarisse ben.usenet at bsb.me.uk
Thu Jan 26 15:29:33 EST 2023


Chris Angelico <rosuav at gmail.com> writes:

> On Thu, 26 Jan 2023 at 08:19, Dino <dino at no.spam.ar> wrote:
>>
>> On 1/23/2023 11:22 PM, Dino wrote:
>> >  >>> b = True
>> >  >>> isinstance(b,bool)
>> > True
>> >  >>> isinstance(b,int)
>> > True
>> >  >>>
>>
>> ok, I read everything you guys wrote. Everyone's got their reasons
>> obviously, but allow me to observe that there's also something called
>> "principle of least surprise".
>>
>> In my case, it took me some time to figure out where a nasty bug was
>> hidden. Letting a bool be a int is quite a gotcha, no matter how hard
>> the benevolent dictator tries to convince me otherwise!
>>
>
> Try this (or its equivalent) in as many languages as possible:
>
> x = (1 > 2)
> x == 0
>
> You'll find that x (which has effectively been set to False, or its
> equivalent in any language) will be equal to zero in a very large
> number of languages. Thus, to an experienced programmer, it would
> actually be quite the opposite: having it NOT be a number would be the
> surprising thing!

I think the programmer's experience would have to have been rather
narrow to be surprised by x not being treated as a number.  I started
with Fortran, Lisp, Pascal and two variants of Algol so I started out
un-surprised by Boolean being a non-arithmetic type.  To be surprised by
x (above) /not/ being treated as a number, an experienced programmer
would have had to have avoided a lot of strictly typed languages.

I've just tried Scheme, Haskell, Common Lisp, Ada, Algol-68, go, ML,
Rust, Ruby, Java, Lua, Prolog and Fortran and they all either say "no
way!" or give false for x == 0.  Of course these are not random choices,
but it shows that Python's design is very far from universal.

But then this is not a numbers game, anyway.  A programmer need only to
have used one or two languages that are rather more strict about types
to find such a thing unsurprising in future.

-- 
Ben.


More information about the Python-list mailing list