bool and int

avi.e.gross at gmail.com avi.e.gross at gmail.com
Wed Jan 25 21:20:55 EST 2023


Chris,

We generally agree albeit I have a question in python with the concept of
being truthy that results in either a Boolean value that boils down to 0 and
1 but in some cases may boil down to the last evaluated argument which
remains in a form that may not be either a Boolean or an integer. I think
this can happen with something like a short-circuit OR. 

Assuming I vaguely remember something real and actual, you can end up with a
variable holding either a Boolean or almost anything and should not use it
in an arithmetical capacity directly but perhaps only use bool(thing) ...

Avi

-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com at python.org> On
Behalf Of Chris Angelico
Sent: Wednesday, January 25, 2023 5:43 PM
To: python-list at python.org
Subject: Re: bool and int

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!

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list