Mailing List Archive

bool and int
$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b = True
>>> isinstance(b,bool)
True
>>> isinstance(b,int)
True
>>>

WTF!

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
Booleans work exactly the way the language documentation says they work:

Booleans (bool<https://docs.python.org/3/library/functions.html#bool>)
These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True"are returned, respectively.

https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Dino <dino@no.spam.ar>
Date: Tuesday, January 24, 2023 at 3:04 PM
To: python-list@python.org <python-list@python.org>
Subject: bool and int
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> b = True
>>> isinstance(b,bool)
True
>>> isinstance(b,int)
True
>>>

WTF!

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jPbvUX9ZXFGYt-q850YI6aQ7ET7BwbF-LIT4XT7MKKwF9OSOgqnaHdM4MbQ7p6YaRCYJYXZ4-XiT3Sko$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jPbvUX9ZXFGYt-q850YI6aQ7ET7BwbF-LIT4XT7MKKwF9OSOgqnaHdM4MbQ7p6YaRCYJYXZ4-XiT3Sko$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 2023-01-24 20:32, Weatherby,Gerard wrote:
> https://peps.python.org/pep-0285/
>
> From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of rbowman <bowman@montana.com>
> Date: Tuesday, January 24, 2023 at 3:01 PM
> To: python-list@python.org <python-list@python.org>
> Subject: Re: bool and int
>
>
> bool is a subtype of integer. I never dug that deep into Python's guts but
> I assume it goes back to boolean being an afterthought in C. Some people
> fancy it up with #defines but I always use int. 0 is false, anything else
> is true.
>
bool was introduced early in Python 2. Before then 0 and 1 were used for
false and true, like in C, which also gained 'false' and 'true'.

For backwards compatibility, bool was made a subclass of int.

> C# is pickier, which I guess is a good thing.

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 24/01/2023 04:22, Dino wrote:
>
> $ python
> Python 3.8.10 (default, Mar 15 2022, 12:22:08)
> [GCC 9.4.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> b = True
> >>> isinstance(b,bool)
> True
> >>> isinstance(b,int)
> True
> >>>
>
That immediately tells you that either
    bool is a subclass of int
    int is a subclass of bool
    bool and int are both subclasses of some other class
In fact the first one is true.
This is not a logical necessity, but the way Python happens to be designed.
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 at 08:22, MRAB <python@mrabarnett.plus.com> wrote:
> For backwards compatibility, bool was made a subclass of int.

Plus, it's really REALLY handy in quite a lot of situations.

> > C# is pickier, which I guess is a good thing.
>

Nope, not a good thing. Actually a highly frustrating thing on those
occasions when I have to write C# code.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 2023-01-25 at 08:58:06 +1100,
Chris Angelico <rosuav@gmail.com> wrote:

> On Wed, 25 Jan 2023 at 08:22, MRAB <python@mrabarnett.plus.com> wrote:
> > For backwards compatibility, bool was made a subclass of int.
>
> Plus, it's really REALLY handy in quite a lot of situations.
>
> > > C# is pickier, which I guess is a good thing.
> >
>
> Nope, not a good thing. Actually a highly frustrating thing on those
> occasions when I have to write C# code.

The usual complaint is that some people write FORTRAN no matter what
language they're actually using. Are you writing Python in C#? ;-)

There's a sweet spot somewhere that includes dynamic typing, high
powered global type inference and optimization systems, a thriving
community, and a metric [boatload] of rock solid libraries.

And an alomost fanatical devotion to the Pope. :-/
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 at 10:32, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
>
> On 2023-01-25 at 08:58:06 +1100,
> Chris Angelico <rosuav@gmail.com> wrote:
>
> > On Wed, 25 Jan 2023 at 08:22, MRAB <python@mrabarnett.plus.com> wrote:
> > > For backwards compatibility, bool was made a subclass of int.
> >
> > Plus, it's really REALLY handy in quite a lot of situations.
> >
> > > > C# is pickier, which I guess is a good thing.
> > >
> >
> > Nope, not a good thing. Actually a highly frustrating thing on those
> > occasions when I have to write C# code.
>
> The usual complaint is that some people write FORTRAN no matter what
> language they're actually using. Are you writing Python in C#? ;-)

Well, let's see. If I were writing C code, I would write:

if (state & PRELAUNCH)

If I were writing Python, it would probably be very different, but it
depends on the API. Could be:

if "PreLaunch" in state:

But the way I have to write it in C# is a messed-up version of C:

if ((state & StartState.PreLaunch) > 0) {

because bool and int are fundamentally different. Using the C style results in:

VelocimeterModule.cs(37,8): error CS0029: Cannot implicitly convert
type `PartModule.StartState' to `bool'

Here's another example. If I were writing C, I would write:

if (TimeWarp_CurrentRateIndex)

Python?

if TimeWarp.CurrentRateIndex:

C#?

if (TimeWarp.CurrentRateIndex > 0)

And, again, if I do it C style, I get:

VelocimeterModule.cs(261,17): error CS0029: Cannot implicitly convert
type `int' to `bool'

I'm pretty sure I've had a case where I wanted to use a boolean in an
arithmetic context, too, but it's less obvious from the final code, so
I can't give an example. So this is synthetic:

autothrust_last_dv *= AT_mode == AT.Idle;

VelocimeterModule.cs(252,4): error CS0019: Operator `*=' cannot be
applied to operands of type `double' and `bool'

So the problem isn't that I'm trying to write Python in C#, but that
I'm trying to write code that would work on pretty much *any other
C-family language*, but doesn't work on C#. I could use those
techniques in plenty of C-derived and C-inspired languages, but nooooo
not in C#, despite looking very much C-inspired. Unfortunately the
truth is that C# is not *actually* C-inspired; it's really Microsoft
Java, so it has all the stupidities of Java:

int x = 3 + (args.length > 1);
test.java:4: error: bad operand types for binary operator '+'

if (args.length) System.out.println("There are args!");
test.java:6: error: incompatible types: int cannot be converted to boolean

But this is hardly a Python-versus-C# thing; it's Java versus most of
the rest of the world, and C# feigns to be part of the C style while
retaining the limitations of Java.

(My apologies if the Java entries look synthetic. It's because they
are, and that's a consequence of me not having ANY reason to write
Java code in, like, ever. In fact, I had to go and install a JDK just
to confirm that Java really did have these limitations.)

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
RE: bool and int [ In reply to ]
Python yet again is being asked why something is the way it is and not as
someone insists it should be. It is a tool to be used the way it SAYS it
works so the bug is perhaps in the user and their expectations.

It is what it is and would break lots of things if changed without much
thought. Every other language I know has similar detractors asking why it is
the way it is.

A useful example where the use of Booleans as 0/1 is commonly used is to
find how many of something satisfy some criteria, such as how many items in
a list are numbers greater than 65 representing test scores that "passed".
It could also be a numpy type of array or a column of a data.frame and so
on. The common method is to create a Boolean data structure (often
implicitly) that is then viewed as a bunch of 0's and 1's and you can count
them to see how many are True (meaning they qualify) or calculate a
percentage simply by taking a mean of the 0/1 values.

There are other ways, but some also use sums of Booleans to calculate things
like any() or all() and I am sure many other things. Yes, all these can be
done another way if Booleans were not allowed to be viewed as very small
integers.

So only use a Boolean in relatively pure situations where arithmetic as a
zero or one is meaningful. In other places, maybe don't. The reality though
is that if you have 10 apples and you get another one if you flip a coin and
it lands on heads. Then 10 + Boolean would indeed be 11. If you have five
losing flips (or tickets or whatever) then 5 * Boolean indeed is a zero.

Python has a different philosophy than some other languages with strong
typing. In some of those, you would not be allowed to add or multiply at
random but would need to convert parts of your calculation to all be the
same, such as a 32-bit integer. You could still do things like I mention
above but only after consciously mapping your Boolean to an actual zero or
one of the kind wanted.

I worry a tad more about the other direction where something like an integer
containing a number like 12 is used in a context where it gets downgraded to
a True/False and later may inadvertently be used as a "1" as the conversion
is not anticipated. There is data loss there more than in the case of a
Boolean becoming a 1.

-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On
Behalf Of 2QdxY4RzWzUUiLuE@potatochowder.com
Sent: Tuesday, January 24, 2023 6:31 PM
To: python-list@python.org
Subject: Re: bool and int

On 2023-01-25 at 08:58:06 +1100,
Chris Angelico <rosuav@gmail.com> wrote:

> On Wed, 25 Jan 2023 at 08:22, MRAB <python@mrabarnett.plus.com> wrote:
> > For backwards compatibility, bool was made a subclass of int.
>
> Plus, it's really REALLY handy in quite a lot of situations.
>
> > > C# is pickier, which I guess is a good thing.
> >
>
> Nope, not a good thing. Actually a highly frustrating thing on those
> occasions when I have to write C# code.

The usual complaint is that some people write FORTRAN no matter what
language they're actually using. Are you writing Python in C#? ;-)

There's a sweet spot somewhere that includes dynamic typing, high powered
global type inference and optimization systems, a thriving community, and a
metric [boatload] of rock solid libraries.

And an alomost fanatical devotion to the Pope. :-/
--
https://mail.python.org/mailman/listinfo/python-list

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 at 12:43, <avi.e.gross@gmail.com> wrote:
> Python has a different philosophy than some other languages with strong
> typing. In some of those, you would not be allowed to add or multiply at
> random but would need to convert parts of your calculation to all be the
> same, such as a 32-bit integer. You could still do things like I mention
> above but only after consciously mapping your Boolean to an actual zero or
> one of the kind wanted.

Python is strongly dynamically typed. You may be thinking of "static
typing" rather than "strong typing" here, and there are plenty of
strongly statically typed languages that allow you to do arithmetic on
booleans (with them usually behaving as if False is 0 and True is 1,
although not always).

> I worry a tad more about the other direction where something like an integer
> containing a number like 12 is used in a context where it gets downgraded to
> a True/False and later may inadvertently be used as a "1" as the conversion
> is not anticipated. There is data loss there more than in the case of a
> Boolean becoming a 1.

Well, yes, but that's no different from a float like 6.25 getting
downgraded to an integer 6. There's a reason that most languages
upcast silently but don't downcast without being asked to.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 12:14:50 +1100, Chris Angelico wrote:


> So the problem isn't that I'm trying to write Python in C#, but that I'm
> trying to write code that would work on pretty much *any other C-family
> language*, but doesn't work on C#. I could use those techniques in
> plenty of C-derived and C-inspired languages, but nooooo not in C#,
> despite looking very much C-inspired. Unfortunately the truth is that C#
> is not *actually* C-inspired; it's really Microsoft Java, so it has all
> the stupidities of Java:

I have the installation media for Visual J++ around here someplace. It
lasted for a few years before Sun sued for non-compliance. There
definitely is some of its DNA in C#.

I prefer C# to C++ but it does have annoyances. It's only a warning that
can be pragma'd but

string foo;

complaining that foo may be null unless you shut it up with

string? foo;

can be frustrating. It has a germ of a good idea for structs (classes)
where some of the members are optional.

The bool hoops definitely are another sore point after a few decades of C.

I can switch gears for Python but the first day or two is painful. I was
getting a bit frustrated until I remembered the range() thing.
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 2023-01-25 at 12:14:50 +1100,
Chris Angelico <rosuav@gmail.com> wrote:

> On Wed, 25 Jan 2023 at 10:32, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:

> > The usual complaint is that some people write FORTRAN no matter what
> > language they're actually using. Are you writing Python in C#? ;-)

> But the way I have to write it in C# is a messed-up version of C:

There's your problem: C# isn't C, it's Java. Java looks like C, too,
but it isn't C, either.

> So the problem isn't that I'm trying to write Python in C#, but that
> I'm trying to write code that would work on pretty much *any other
> C-family language*, but doesn't work on C#. I could use those
> techniques in plenty of C-derived and C-inspired languages, but nooooo
> not in C#, despite looking very much C-inspired. Unfortunately the
> truth is that C# is not *actually* C-inspired; it's really Microsoft
> Java, so it has all the stupidities of Java:

There. Even ChrisA agrees with me. ;-)

So, I think what you're trying to say is that you prefer the razor sharp
quality of truthiness to the zen of explicit being better than implicit.

To bring this back to Python (sorry), blurring the line between booleans
and integers is an old machine language trick, born of the days when we
measured memory in bytes (and large sums of cash!) rather than gigs[0].
In Python3, there's no more reason to use a boolean value as integer
(whether to accumulate values or to test a value against zero) as there
is to use a string (e.g., from an HTML form) as an integer.

[0] I remember meetings where the agenda was to allocate memory (yes, at
design time) for a particular value, and the answer was along the lines
of "you can have these five bits, and this would have taken a lot less
time had you told us sooner that you needed that value to persist across
input messages."

> But this is hardly a Python-versus-C# thing; it's Java versus most of
> the rest of the world, and C# feigns to be part of the C style while
> retaining the limitations of Java.

IMO, the problem started when Java tried to be too much like C to
attract (or should I say "trap"?) C developers.

> (My apologies if the Java entries look synthetic. It's because they
> are, and that's a consequence of me not having ANY reason to write
> Java code in, like, ever. In fact, I had to go and install a JDK just
> to confirm that Java really did have these limitations.)

They used Java at my last job (as in, the last job I had before I
retired), and it was absolutely awful, for any number of reasons, the
gymnastics (on many levels) required to support "primitive types" being
one of them.
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 at 22:55, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
>
> On 2023-01-25 at 12:14:50 +1100,
> Chris Angelico <rosuav@gmail.com> wrote:
>
> > On Wed, 25 Jan 2023 at 10:32, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
>
> > > The usual complaint is that some people write FORTRAN no matter what
> > > language they're actually using. Are you writing Python in C#? ;-)
>
> > But the way I have to write it in C# is a messed-up version of C:
>
> There's your problem: C# isn't C, it's Java. Java looks like C, too,
> but it isn't C, either.
>
> > So the problem isn't that I'm trying to write Python in C#, but that
> > I'm trying to write code that would work on pretty much *any other
> > C-family language*, but doesn't work on C#. I could use those
> > techniques in plenty of C-derived and C-inspired languages, but nooooo
> > not in C#, despite looking very much C-inspired. Unfortunately the
> > truth is that C# is not *actually* C-inspired; it's really Microsoft
> > Java, so it has all the stupidities of Java:
>
> There. Even ChrisA agrees with me. ;-)
>
> So, I think what you're trying to say is that you prefer the razor sharp
> quality of truthiness to the zen of explicit being better than implicit.

Not sure what you mean here. If you want to bring this back to the Zen
of Python, I would reference "practicality beats purity". We can do
arithmetic on integers and floats without having to explicitly cast
one to the other, because there's really no point in distinguishing
them. We can do that with booleans and other types, too.

> To bring this back to Python (sorry), blurring the line between booleans
> and integers is an old machine language trick, born of the days when we
> measured memory in bytes (and large sums of cash!) rather than gigs[0].
> In Python3, there's no more reason to use a boolean value as integer
> (whether to accumulate values or to test a value against zero) as there
> is to use a string (e.g., from an HTML form) as an integer.

Strongly disagree. There is PLENTY of practical value in using
booleans as numbers. This is nothing to do with counting bytes, and
everything to do with how useful it is in practice.

> > But this is hardly a Python-versus-C# thing; it's Java versus most of
> > the rest of the world, and C# feigns to be part of the C style while
> > retaining the limitations of Java.
>
> IMO, the problem started when Java tried to be too much like C to
> attract (or should I say "trap"?) C developers.

Maybe. No idea. In any case, Java's restrictiveness is VERY different
from the way Python works (for instance, operator overloading, the way
strings are handled, etc), and I don't think people here want the
shackles of Java.

> > (My apologies if the Java entries look synthetic. It's because they
> > are, and that's a consequence of me not having ANY reason to write
> > Java code in, like, ever. In fact, I had to go and install a JDK just
> > to confirm that Java really did have these limitations.)
>
> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

Yeah. "Primitive types" being different from "boxed types" is an
unnecessary and arbitrary distinction, like between types and classes,
or old-style classes and those that subclass object. Neither is needed
in modern Python, neither is beneficial.

Keeping bool as a subclass of int has never been in dispute. Nor has
the treatment of other types in a boolean context. I can't find
anything in the Python 3000 proposals that ever even suggested
changing either; the best I can find is this reference in PEP 285
which rejected the notions:

"""
Should we strive to eliminate non-Boolean operations on bools in the
future, through suitable warnings, so that for example True+1 would
eventually (in Python 3000) be illegal?

=> No.

Should we strive to require that Boolean operations (like “if”, “and”,
“not”) have a bool as an argument in the future, so that for example
“if []:” would become illegal and would have to be written as “if
bool([]):” ???

=> No!!!
"""

See: https://peps.python.org/pep-0285/

C# is a pain to work with because it fails on these points of
practicality. I'm morbidly curious as to how C# fanatics justify this
sort of thing, given that so many languages just DTRT without needing
to be told.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 1/25/2023 6:53 AM, 2QdxY4RzWzUUiLuE@potatochowder.com wrote:
> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

In my one serious java program, a Tomcat application, I use a small
amount of Java for the servlets and startup filters, and Jython for the
heart of the computing. Thank goodness for Jython!
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On 2023-01-25 at 23:11:37 +1100,
Chris Angelico <rosuav@gmail.com> wrote:

> On Wed, 25 Jan 2023 at 22:55, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:

> > So, I think what you're trying to say is that you prefer the razor sharp
> > quality of truthiness to the zen of explicit being better than implicit.
>
> Not sure what you mean here. If you want to bring this back to the Zen
> of Python, I would reference "practicality beats purity". We can do
> arithmetic on integers and floats without having to explicitly cast
> one to the other, because there's really no point in distinguishing
> them. We can do that with booleans and other types, too.

My point was that we all have our own preferences and biases, and in
this case, I think you and I lean in opposite directions, and Python is
big enough for both of us.

> > To bring this back to Python (sorry), blurring the line between booleans
> > and integers is an old machine language trick, born of the days when we
> > measured memory in bytes (and large sums of cash!) rather than gigs[0].
> > In Python3, there's no more reason to use a boolean value as integer
> > (whether to accumulate values or to test a value against zero) as there
> > is to use a string (e.g., from an HTML form) as an integer.
>
> Strongly disagree. There is PLENTY of practical value in using
> booleans as numbers. This is nothing to do with counting bytes, and
> everything to do with how useful it is in practice.

IMO, the difference in readability between

autothrust_last_dv *= AT_mode == AT.Idle;

and

if(AT_mode != AT.Idle)
autothrust_last_dv = 0;

outweighs the practicality, whether C, C#, Java, or Python (ignoring the
insignificant differences in syntax).

Maintainability, too: as soon as there's something else to do when
AT_mode isn't AT.Idle, I'm going to rewrite the first one as the second
one anyway. (No, I won't mess up the braces.)

I could argue that the only reason the first one is readable at all is
that we've both been exposed to languages where fanatics assume that
True is 1 and False is 0. I've also written low-level code with
hardware fanatics who insist that True is 0 and False is -1 (or 255,
depending on how much math they know). In a posix shell script (or a
program that knows it might be run inside such a script), 0 is "true"
and non-zero is "false." My point here is that you have to understand
how to work within whatever environment you're using, and that future
programmers (and future you!) will have to deal with your choices
regardless of their background, biases, and preferences.

> C# is a pain to work with because it fails on these points of
> practicality. I'm morbidly curious as to how C# fanatics justify this
> sort of thing, given that so many languages just DTRT without needing
> to be told.

They say that Perl is practical. ;-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, 25 Jan 2023 06:53:44 -0500, 2QdxY4RzWzUUiLuE wrote:


> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

My first brush with Java was around '98 when it was first becoming
popular. To familiarize myself with the AWT I decided to write a simple
IDE for the AVR microcontrollers. What a disaster. The UI wasn't bad but
the instructions for 8-bit processors require a lot of bit fiddling that
was extraordinarily difficult in Java.

Then they came out with Swing and the assumption if the app ran with
glacial slowness you should get a faster machine.

The company I work for has one Java app created around 2000 as a cross
platform solution as people moved to Windows. Originally it ran as an
applet but when that window was slammed shut it became increasingly
unwieldy.

For what I'm developing today I used either .NET C# or Python3. The .NET
UI's on Linux aren't quite there yet but back end applications are fine.
PyQt (PySide actually. If there is a way to screw up commercial licensing
Qt will find it) is fine.
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Thu, 26 Jan 2023 at 03:19, <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
> > Strongly disagree. There is PLENTY of practical value in using
> > booleans as numbers. This is nothing to do with counting bytes, and
> > everything to do with how useful it is in practice.
>
> IMO, the difference in readability between
>
> autothrust_last_dv *= AT_mode == AT.Idle;
>
> and
>
> if(AT_mode != AT.Idle)
> autothrust_last_dv = 0;
>
> outweighs the practicality, whether C, C#, Java, or Python (ignoring the
> insignificant differences in syntax).

Yeah, that example was completely synthetic and not really a good
showcase. But what often comes up is either multiplying a string by a
boolean (equivalent to "have this string if this is true") or
subscripting something with a boolean.

> I could argue that the only reason the first one is readable at all is
> that we've both been exposed to languages where fanatics assume that
> True is 1 and False is 0.

I'm fine with any definition as long as it's dependable.

> I've also written low-level code with
> hardware fanatics who insist that True is 0 and False is -1 (or 255,
> depending on how much math they know).

BASIC was like that too, although it (at least, the versions I used in
my childhood) didn't have "True" and "False", you just got the actual
values -1 and 0. They were the other way around compared to what
you're saying here though.

> In a posix shell script (or a
> program that knows it might be run inside such a script), 0 is "true"
> and non-zero is "false."

And that's a consequence of a system wherein there is only one concept
of "success", but many concepts of "failure". Whoever devised that
system was clearly a pessimist :)

> My point here is that you have to understand
> how to work within whatever environment you're using, and that future
> programmers (and future you!) will have to deal with your choices
> regardless of their background, biases, and preferences.

That's always the case, though.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Tue, 24 Jan 2023 20:16:31 -0500, Mike Baskin <mikebaskin6538@yahoo.com>
declaimed the following:

>Will all of you please stop sending me emails
>

Nobody is sending "you" emails deliberately (unless they have a poorly
[to me] set up client that sends to the list AND the person who wrote the
message they replied to) -- they are sending them to a Python mailing list.
The mailing list only sends them to /subscribed/ users.

Read the headers in the message for instructions...

List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>


--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
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!



--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Thu, 26 Jan 2023 at 08:19, Dino <dino@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
RE: bool and int [ In reply to ]
Dino,

There is no such things as a "principle of least surprise" or if you insist
there is, I can nominate many more such "rules" such as "the principle of
get out of my way and let me do what I want!"

Computer languages with too many rules are sometimes next to unusable in
practical situations.

I am neither defending or attacking choices Python or other languages have
made. I merely observe and agree to use languages carefully and as
documented.

But consider that the history of computer science when it came to counting
numbers depends on bits. Pretty much everything is in base two. When space
was a major concern, or efficiency, people often used smaller units when
possible. If you look at something like how one stored files on UNIX, they
set aside a group of bits of some size as part of some larger entity and
each bit represented a BOOLEAN concept of 1 and 0 to mean is that bit set to
some sort of ON or off. Three of those bits controlled whether the owner of
a file had permission to read, write or execute the file. Another three
governed the same idea for everyone listed as being in the same group and
another three listed permissions for "other". The whole thing took up more
room in something larger where perhaps 14 bytes (of 8 bits each) were set
aside to hold a filename and other parts held things like perhaps a link
count. At some point they noticed the chink had a few unused bits and
invented a purpose for them and patented the setuid bit concept and the
setgid bit.

So back to integers. You can use 16 bits in a signed or unsigned manner and
cover numbers between a low and a high. You can use 64 bits or 128 bits or
whatever makes you happy and it remains an integer albeit trying to do
arithmetic between them can result in an overflow situation and the hardware
often does not trivially support it. It turned out that often there was a
use for 8 bits even though they hold only 256 possible integers and before
the alphabets grew to need more room, that was enough space for an ASCII or
EBCDIC character. Sometimes you did things at the nibble level of 4 bits or
a hex digit. Booleans were even simpler at 1 bit. But all SIZES can be used
to hold some range of integers. Modern python has made some extensions that
let you store integers of unlimited size but underneath it all, the
operations are still dealing with the same ideas as shorter versions
including ones that hold more limited numbers down to binary/Boolean.

So if you want to save space in memory or on a hard disk or sending across
the internet, you well may want the ability to set aside a "char" to hold
smallish numbers or treat a Boolean value as a "1" and so on. If you know
what you are doing, it is not much of a surprise. On many systems, there may
well be some registers that load 32 or 64 bits and then you use them for
something like addition. If I supply a 16-bit or 8-bit or even 1-bit
quantity, the software generally ends up putting it into the standard size
register and pads unused areas with zeroes. No big deal. If the number is
too large to fit, as with any larger integer in python, then the software
does whatever it needs to such as calculating how many chunks need adding
and doing the addition in the same registers in smaller chunks while
managing any carryover and finally assembling the possibly longer result.

Floating point is a slightly different animal than the others that arguably
are all of a similar if not identical type. But even there, your storage has
two components which are actually both seen as integers of sorts. 6.02 times
ten to the 23rd might also be written as 602 times ten to the 21st and now
you have two integers you can use in calculations that registers do on
integers and recombine into a new floating point format. Or, of course, you
might have hardware that does the work.

If you move on to complex variables, they tend to be a sort of named tuple
containing a real and imaginary part with special rules on how to add and do
other mathematical operations. Underneath it all, they are often implemented
as a pair of linked floating point structures. And in one sense, all real
numbers represented in a floating point variable are a strict subset of
complex numbers with imaginary part being zero. All integers are in a sense
floating point numbers with fractional part (meaning beyond the decimal
point) being all zeroes. Similarly, all smaller integral types such as
bytes are Booleans are a limited subset.

So some of us who know a bit about CS and not just this language, are less
often surprised by a choice of implementations. We often do not mix things
but when we do, we know what we are doing much of the time and appreciate
how easily it can be done. Consider what happens if you want to circularly
permute alphabetic characters of the English Alphabet by 13, sometimes
called rot13. There are quite a few ways to do it but one of them depends on
the fact that the numerical value in ASCII of the letter 'A' is one less
than of the next letter, 'B' and so on to 'Z'. They are contiguous but note
upper and lower cases letters are not back to back. So a piece of code that
says that if a character is between the numerical representation of 'A' and
halfway to the end, then add 13, and if it is higher, then add 13 and
subtract 26 (or obviously just subtract 13) to slide it circularly back, is
a valid way to do the permutation. But it involves adding what may seem to
be a 32-bit integer containing a number like 13 or 26 to an 8-bit character
resulting in an 8-bit character. Should that be illegal?

Well, in a sense it is illegal and you should be forced to create something
of type char that holds whatever 13 is, which probably is a
control-character and then either use operations that add or subtract 8-bit
items, OR you may widen the character to 32 bits and do the math with a
32-bit representation of 13/26 then narrow the result back into eight bits.
But lots of systems know how to automate this for you or even do it more
efficiently than you might have done on your own and do it differently on
different computer architectures. One goal of programming is to make life as
easy as possible for a programmer to be productive or make fewer errors and
so on. Sometimes not being surprised is a valid goal. But a language like
Python may not lean the way you think.

I once bashed my head at languages like PASCAL and even C as it often took
some work to do things like process a list of heterogenous contents
including perhaps some I may have no idea about at compile time. You
sometimes needed to convince the compiler to loosen up on rules such as by
declaring a union of several types. Python often does not care what anything
is and just passes it on. You, as the writer of a function may have to check
things like whether what you were passed is hashable or is of a numeric
type. You may simply take any argument(s) and coerce them into a new list
object to guarantee that whatever it is can now handle what lists supply.
This means you are often free to use the function with arguments that are
tuples or iterators and not just lists. Yes, someone using the function may
yet surprise you and you may want to write defensive code that checks
up-front and stops if called in an unexpected way. But you can write the
main function fairly quickly while assuming no surprises and bullet-proof it
later once it seems to work for what you want. The alternative is to keep
fighting with a compiler (or a static checker like mpy) before anything gets
done.

The surprise there is when they fire you from your job for not seeming to do
much for many months.

Having said that, I have had many surprises in many languages such as some
that help you so much that they handle 3 + "two" for you and return 5 or
maybe "five" rather than suggest you may have name an error and meant 3 +
int(english_number_to_string("two")) or perhaps "3" + "two" ...

I am surprised how this message got this long! Aaargh!





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

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!



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

--
https://mail.python.org/mailman/listinfo/python-list
RE: bool and int [ In reply to ]
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@python.org> On
Behalf Of Chris Angelico
Sent: Wednesday, January 25, 2023 5:43 PM
To: python-list@python.org
Subject: Re: bool and int

On Thu, 26 Jan 2023 at 08:19, Dino <dino@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

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Wed, Jan 25, 2023 at 01:01:24PM +1100, Chris Angelico wrote:
> On Wed, 25 Jan 2023 at 12:43, <avi.e.gross@gmail.com> wrote:
> > Python has a different philosophy than some other languages with strong
> > typing. In some of those, you would not be allowed to add or multiply at
> > random but would need to convert parts of your calculation to all be the
> > same, such as a 32-bit integer. You could still do things like I mention
> > above but only after consciously mapping your Boolean to an actual zero or
> > one of the kind wanted.
>
> Python is strongly dynamically typed. You may be thinking of "static
> typing" rather than "strong typing" here,

You often insist on this but frankly it does not jibe with the
definitions of "strongly typed language" that I was taught or that I
still see used commonly, including in literature and on sites that aim
to teach people about computer science, which basically amount to:

1. A language whose variables are defined by type, and can only hold
that type, typically but not necessarily compiled.
2. A language which strongly enforces restrictions on mixing or
operating on, and/or implicitly converting different data types,
with the implication that the structure of types is well-defined
and rigid.

Python conforms to neither--its VARIABLES are normally untyped (though
the object data they hold obviously is). Object instances can have
new fields added to them on the fly, willy-nilly, and Python allows
for any object which has an interface--or rather only the portion of
interface you care about in the moment--like the one it expects, to be
used in a given context, i.e. duck typing. Useful properties (when
used carefully!) but not intuitively consistent with the idea of
"strong typing" and potentially dangerous if care is not taken. When
YOU say that Python is strongly typed, you're using some other
definition--one that is perhaps technically correct, but seemingly
quite a lot of people in the field--including active students, college
professors, and seasoned professionsals--are unaware of...

The above usages are common and widespread, widely accepted--which is
inherently what makes word usages correct--and you very obviously know
full well what people mean when they use them; so "correcting" people
who use them seems rather unhelpful (certainly without detailing what
you think it means), inappropriate, and arguably just simply wrong.
It seems to serve no purpose other than to make communication harder,
and possibly to irritate people. I would encourage you to consider
ceasing the practice, so as to not needlessly detract from the
otherwise usually good info you routinely provide...

And FWIW if you want some references, a google search will return
voluminous examples of people using the term as I described--from
acadamia to business--but here are just a few:

https://www.cs.cornell.edu/courses/cs1130/2012sp/1130selfpaced/module1/module1part4/strongtyping.html
https://courses.yarrahills.vic.edu.au/moodle/mod/book/view.php?id=18778&chapterid=28
https://www.oreilly.com/library/view/mastering-c-and/9781785884375/ch02s02.html
https://www.postgresql.org/docs/current/typeconv-overview.html
https://www.sciencedirect.com/topics/computer-science/strongly-typed-language
https://www.techtarget.com/whatis/definition/strongly-typed

--
https://mail.python.org/mailman/listinfo/python-list
RE: bool and int [ In reply to ]
Like Chris, I appreciate precision when it matters but since I am not
writing a textbook here, I often talk more informally.

There are many variations on now variables or objects are treated
differently in certain languages and when I said "STRONG" I simply meant a
sort of opposite to "WEAK". I could have used any number of silly words like
"mighty typing" and most would have been meaningless.

As python@bladeshadow.org points out, from some perspectives, Python plays
quite fast and lose about what a variable can refer to. It is not a bug but
a proud feature of the language that you can easily do all kinds of things
with a kind of polymorphism (and I do NOT want to hear how I misused that
term in some technical way).

I have been reading about the ways Python keeps amending the ways you can
tell a program about the types a variable can hold and it gets quite amusing
in some ways. First, almost anything you write has to be IGNORED at
run-time. You are sort of just slowing down things and making your program
text longer, albeit the byte-compiled files may toss much of that. The main
purpose if of static type checkers like mpy to badger you until you come up
with just the right incantation and even then, your program can have plenty
of bugs and fail at run-time. There is a rich and seemingly ever-growing new
set of quasi-language features for specifying more closely what a function
expects as arguments and what it might return and some are potentially very
useful except for the minor detail that at runtime, your suggestion that
your function takes only objects that implement some protocol such as
defining __lt__ is absolutely ignored. All that mpy can do is static
testing of what you CLAIM you want.

I am not making fun, of course, but in code I develop, I have negligible
interest in using the optional typing system and checking at first. It can
truly slow things down and some of the constraints can turn out to be too
tight if you later find the method you used excludes lots of things people
would use it on. I prefer having working code before I mark it up to be less
legible but in a way that finds some possible errors, or maybe mainly forces
me to change the markup to something else. And, if I really want my code to
CATCH errors when running, the beginning of many functions will have to
contain active tests such as checking if it is one of the types I want it to
support or implements some protocol, and if not, handle the error
gracefully. Such code can be way more detailed or correct than the type
system or may be way worse but it can also in some sense be a
self-documentation that some can read easier than trying to enforce strong
typing.

If I was working on a large project with many people and the organization
had all kinds of protocols and rules, then sure, you follow them or leave.
But at some point you may ask the dumb question of why they are using Python
at all, rather than a much "safer" language designed to minimize any ability
to make many errors as the program refuses to run until highly polished?


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

On Wed, Jan 25, 2023 at 01:01:24PM +1100, Chris Angelico wrote:
> On Wed, 25 Jan 2023 at 12:43, <avi.e.gross@gmail.com> wrote:
> > Python has a different philosophy than some other languages with
> > strong typing. In some of those, you would not be allowed to add or
> > multiply at random but would need to convert parts of your
> > calculation to all be the same, such as a 32-bit integer. You could
> > still do things like I mention above but only after consciously
> > mapping your Boolean to an actual zero or one of the kind wanted.
>
> Python is strongly dynamically typed. You may be thinking of "static
> typing" rather than "strong typing" here,

You often insist on this but frankly it does not jibe with the definitions
of "strongly typed language" that I was taught or that I still see used
commonly, including in literature and on sites that aim to teach people
about computer science, which basically amount to:

1. A language whose variables are defined by type, and can only hold
that type, typically but not necessarily compiled.
2. A language which strongly enforces restrictions on mixing or
operating on, and/or implicitly converting different data types,
with the implication that the structure of types is well-defined
and rigid.

Python conforms to neither--its VARIABLES are normally untyped (though the
object data they hold obviously is). Object instances can have new fields
added to them on the fly, willy-nilly, and Python allows for any object
which has an interface--or rather only the portion of interface you care
about in the moment--like the one it expects, to be used in a given context,
i.e. duck typing. Useful properties (when used carefully!) but not
intuitively consistent with the idea of "strong typing" and potentially
dangerous if care is not taken. When YOU say that Python is strongly typed,
you're using some other definition--one that is perhaps technically correct,
but seemingly quite a lot of people in the field--including active students,
college professors, and seasoned professionsals--are unaware of...

The above usages are common and widespread, widely accepted--which is
inherently what makes word usages correct--and you very obviously know full
well what people mean when they use them; so "correcting" people who use
them seems rather unhelpful (certainly without detailing what you think it
means), inappropriate, and arguably just simply wrong.
It seems to serve no purpose other than to make communication harder, and
possibly to irritate people. I would encourage you to consider ceasing the
practice, so as to not needlessly detract from the otherwise usually good
info you routinely provide...

And FWIW if you want some references, a google search will return voluminous
examples of people using the term as I described--from acadamia to
business--but here are just a few:

https://www.cs.cornell.edu/courses/cs1130/2012sp/1130selfpaced/module1/modul
e1part4/strongtyping.html
https://courses.yarrahills.vic.edu.au/moodle/mod/book/view.php?id=18778&chap
terid=28
https://www.oreilly.com/library/view/mastering-c-and/9781785884375/ch02s02.h
tml
https://www.postgresql.org/docs/current/typeconv-overview.html
https://www.sciencedirect.com/topics/computer-science/strongly-typed-languag
e
https://www.techtarget.com/whatis/definition/strongly-typed

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

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
On Thu, 26 Jan 2023 04:10:30 +1100, Chris Angelico wrote:


> BASIC was like that too, although it (at least, the versions I used in
> my childhood) didn't have "True" and "False", you just got the actual
> values -1 and 0. They were the other way around compared to what you're
> saying here though.

I've see header files from people with boolean envy that are something
like

#define FALSE 0
#define TRUE ~FALSE

--
https://mail.python.org/mailman/listinfo/python-list
Re: bool and int [ In reply to ]
I can?t help but wonder if there exists some Java forum /mailing list going on about how horrible Python is.

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of rbowman <bowman@montana.com>
Date: Wednesday, January 25, 2023 at 12:25 PM
To: python-list@python.org <python-list@python.org>
Subject: Re: bool and int
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On Wed, 25 Jan 2023 06:53:44 -0500, 2QdxY4RzWzUUiLuE wrote:


> They used Java at my last job (as in, the last job I had before I
> retired), and it was absolutely awful, for any number of reasons, the
> gymnastics (on many levels) required to support "primitive types" being
> one of them.

My first brush with Java was around '98 when it was first becoming
popular. To familiarize myself with the AWT I decided to write a simple
IDE for the AVR microcontrollers. What a disaster. The UI wasn't bad but
the instructions for 8-bit processors require a lot of bit fiddling that
was extraordinarily difficult in Java.

Then they came out with Swing and the assumption if the app ran with
glacial slowness you should get a faster machine.

The company I work for has one Java app created around 2000 as a cross
platform solution as people moved to Windows. Originally it ran as an
applet but when that window was slammed shut it became increasingly
unwieldy.

For what I'm developing today I used either .NET C# or Python3. The .NET
UI's on Linux aren't quite there yet but back end applications are fine.
PyQt (PySide actually. If there is a way to screw up commercial licensing
Qt will find it) is fine.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZHaXF58tWtyogy37PB6b9DH-gINgbVLuU64V4RovArDpnC5jjiQ$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iVrdROvxcoNV-GhzezJe8fJSLSAUoPkZHaXF58tWtyogy37PB6b9DH-gINgbVLuU64V4RovArDpnC5jjiQ$>
--
https://mail.python.org/mailman/listinfo/python-list

1 2  View All