Re: for -- else: what was the motivation?

2022-11-05 Thread Peter J. Holzer
On 2022-10-22 15:04:58 +0200, Peter J. Holzer wrote:
> On 2022-10-19 12:10:52 +1100, Chris Angelico wrote:
> > On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer  wrote:
> > > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > > > http://literateprogramming.com/
> > >
> > > Right. That's one of the inspirations for my comment.
> > >
> > > But literate programming is of course still very much rooted in the
> > > "linear text representation" paradigm. You have one definite source
> > > which is a linear text.
> > >
> > > In a world of IDEs, databases and hypertext that's probably not the best
> > > we can do. As Raymond Hettinger would say, "there must be a better way".
> > >
> > > It would be very different from mainstream programming languages,
> > > however. And ideally you would want it to integrate with a lot of other
> > > infrastructure. So that alone might make it a non-starter, even if it
> > > was really good (which realistically early iterations wouldn't be).
> > 
> > There are special-purpose languages like Scratch which are not simple
> > text in that form.
> 
> Yes, I know.
> 
> It has a different goal though: Scratch tries to establish a friendly
> learning environment. Get rid of typing and syntax errors that beginners
> find so frustrating.
> 
> What I'm interested in is an enviroment for developing medium-sized real
> applications.

Late addendum: Watch

["Stop Writing Dead Programs" by Jack Rusher (Strange Loop 
2022)](https://www.youtube.com/watch?v=8Ab3ArE8W3s)

for an overview of some ideas about programming environments.

hp


-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-22 Thread Drew Pierson
the fuck?

On Sat, Oct 22, 2022 at 9:06 AM Peter J. Holzer  wrote:

> On 2022-10-19 12:10:52 +1100, Chris Angelico wrote:
> > On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer  wrote:
> > > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > > > http://literateprogramming.com/
> > >
> > > Right. That's one of the inspirations for my comment.
> > >
> > > But literate programming is of course still very much rooted in the
> > > "linear text representation" paradigm. You have one definite source
> > > which is a linear text.
> > >
> > > In a world of IDEs, databases and hypertext that's probably not the
> best
> > > we can do. As Raymond Hettinger would say, "there must be a better
> way".
> > >
> > > It would be very different from mainstream programming languages,
> > > however. And ideally you would want it to integrate with a lot of other
> > > infrastructure. So that alone might make it a non-starter, even if it
> > > was really good (which realistically early iterations wouldn't be).
> >
> > There are special-purpose languages like Scratch which are not simple
> > text in that form.
>
> Yes, I know.
>
> It has a different goal though: Scratch tries to establish a friendly
> learning environment. Get rid of typing and syntax errors that beginners
> find so frustrating.
>
> What I'm interested in is an enviroment for developing medium-sized real
> applications. Somewhere in the several person-months to several
> person-years of effort, hundreds of user-stories, maybe thousands of
> bug-reports and change-requests over its life-time.
>
> The people using such a system/language would be professional
> programmers. They probably don't need much help to get the syntax of a
> for loop right. What they do need, though:
>
> * Cross-reference between requirements and code. (Yes, you can write
>   comments, yes, you will hopefully have meaningful commit messages.
>   Still, I see a lot of room for improvements there)
> * Cross-references between related parts of the code. (Yes, many IDEs
>   can jump to the definition of an instance or list all instances of a
>   definiton, But sometimes the relationship isn't that mechanic. And
>   yes, you can use comments fpr that, too)
> * Views which highlight some parts of the code and omit others. (Folding
>   editors do that in a very limited fashion)
>   * For example, I might want to see only the code proper when I'm
> focusing on an algorithm or I might want to see lots of context
> (type definitions, requirements, test results, ...)
>   * Classes often have quite a lot of methods with no natural order.
> Being able to view only a subset of them in some custom order may
> help.
>   * Going back to the core idea of literate programming: Especially
> views which show some requirement(s) together with the code that
> implements them plus some explanation why that implementation was
> chosen.
>
> Presented like this, it's clear that the "language" (i.e. the file
> format) is probably the smallest part of the problem. How the user can
> view the program, how they can edit it, and how to keep the whole thing
> manageable is a much bigger question. And it would probably be a good
> idea to start at the system level and not at the language level.
>
>
> > My Twitch channel bot has a command executor whose language, if you
> > call it that, is basically JSON - and the way to edit those commands
> > is very Scratch-inspired.
>
> I designed a graphical filter language for database queries once. The idea
> was that you could combine various operations (selects, projections,
> grouping, transformations, ...) into pipelines via a web interface. We
> did implement it (sadly it wasn't me who did it), and it turned out to
> be a lot harder than I thought to make that actually usable.
>
> And of course there have been lots of CASE tools over the years. That
> seems to have been mostly a fad of 90s. Still, there were some good
> ideas there (although not alway implemented well), and something bubbles
> back up every now and then.
>
> hp
>
> --
>_  | Peter J. Holzer| Story must make more sense than reality.
> |_|_) ||
> | |   | h...@hjp.at |-- Charles Stross, "Creative writing
> __/   | http://www.hjp.at/ |   challenge!"
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-22 Thread Peter J. Holzer
On 2022-10-22 15:04:58 +0200, Peter J. Holzer wrote:
> On 2022-10-19 12:10:52 +1100, Chris Angelico wrote:
> > On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer  wrote:
> > > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > > > http://literateprogramming.com/
> > >
> > > Right. That's one of the inspirations for my comment.
> > >
> > > But literate programming is of course still very much rooted in the
> > > "linear text representation" paradigm. You have one definite source
> > > which is a linear text.
> > >
> > > In a world of IDEs, databases and hypertext that's probably not the best
> > > we can do. As Raymond Hettinger would say, "there must be a better way".
> > >
> > > It would be very different from mainstream programming languages,
> > > however. And ideally you would want it to integrate with a lot of other
> > > infrastructure. So that alone might make it a non-starter, even if it
> > > was really good (which realistically early iterations wouldn't be).
> > 
> > There are special-purpose languages like Scratch which are not simple
> > text in that form.
> 
> Yes, I know.
> 
> It has a different goal though: Scratch tries to establish a friendly
> learning environment. Get rid of typing and syntax errors that beginners
> find so frustrating.
> 
> What I'm interested in is an enviroment for developing medium-sized real
> applications. Somewhere in the several person-months to several
> person-years of effort, hundreds of user-stories, maybe thousands of
> bug-reports and change-requests over its life-time.
[...]
> And of course there have been lots of CASE tools over the years.

A possibly totally different approach:

There are tools[1] for authors which are supposed to help them keep all
their characters, events, timelines, etc. in order. I have never used
one (I don't plan to write a novel anytime soon), but what I've heard of
them sounds like it would be useful for software-development, too.

hp

[1] E.g. Campfire (https://www.campfirewriting.com/)

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-22 Thread Peter J. Holzer
On 2022-10-19 12:10:52 +1100, Chris Angelico wrote:
> On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer  wrote:
> > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > > http://literateprogramming.com/
> >
> > Right. That's one of the inspirations for my comment.
> >
> > But literate programming is of course still very much rooted in the
> > "linear text representation" paradigm. You have one definite source
> > which is a linear text.
> >
> > In a world of IDEs, databases and hypertext that's probably not the best
> > we can do. As Raymond Hettinger would say, "there must be a better way".
> >
> > It would be very different from mainstream programming languages,
> > however. And ideally you would want it to integrate with a lot of other
> > infrastructure. So that alone might make it a non-starter, even if it
> > was really good (which realistically early iterations wouldn't be).
> 
> There are special-purpose languages like Scratch which are not simple
> text in that form.

Yes, I know.

It has a different goal though: Scratch tries to establish a friendly
learning environment. Get rid of typing and syntax errors that beginners
find so frustrating.

What I'm interested in is an enviroment for developing medium-sized real
applications. Somewhere in the several person-months to several
person-years of effort, hundreds of user-stories, maybe thousands of
bug-reports and change-requests over its life-time.

The people using such a system/language would be professional
programmers. They probably don't need much help to get the syntax of a
for loop right. What they do need, though:

* Cross-reference between requirements and code. (Yes, you can write
  comments, yes, you will hopefully have meaningful commit messages. 
  Still, I see a lot of room for improvements there)
* Cross-references between related parts of the code. (Yes, many IDEs
  can jump to the definition of an instance or list all instances of a
  definiton, But sometimes the relationship isn't that mechanic. And
  yes, you can use comments fpr that, too)
* Views which highlight some parts of the code and omit others. (Folding
  editors do that in a very limited fashion)
  * For example, I might want to see only the code proper when I'm
focusing on an algorithm or I might want to see lots of context
(type definitions, requirements, test results, ...)
  * Classes often have quite a lot of methods with no natural order.
Being able to view only a subset of them in some custom order may
help.
  * Going back to the core idea of literate programming: Especially
views which show some requirement(s) together with the code that
implements them plus some explanation why that implementation was
chosen.

Presented like this, it's clear that the "language" (i.e. the file
format) is probably the smallest part of the problem. How the user can
view the program, how they can edit it, and how to keep the whole thing
manageable is a much bigger question. And it would probably be a good
idea to start at the system level and not at the language level.


> My Twitch channel bot has a command executor whose language, if you
> call it that, is basically JSON - and the way to edit those commands
> is very Scratch-inspired.

I designed a graphical filter language for database queries once. The idea
was that you could combine various operations (selects, projections,
grouping, transformations, ...) into pipelines via a web interface. We
did implement it (sadly it wasn't me who did it), and it turned out to
be a lot harder than I thought to make that actually usable.

And of course there have been lots of CASE tools over the years. That
seems to have been mostly a fad of 90s. Still, there were some good
ideas there (although not alway implemented well), and something bubbles
back up every now and then.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-18 Thread Chris Angelico
On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer  wrote:
>
> On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > > which had special combinations for all the BASIC keywords). And if you
> > > go this way, why not go a step further and dissociate the program from
> > > its linear text representation? Add footnotes, different views,
> > > hyperlinks, format mathematical expressions like formulas, etc.
> >
> > http://literateprogramming.com/
>
> Right. That's one of the inspirations for my comment.
>
> But literate programming is of course still very much rooted in the
> "linear text representation" paradigm. You have one definite source
> which is a linear text.
>
> In a world of IDEs, databases and hypertext that's probably not the best
> we can do. As Raymond Hettinger would say, "there must be a better way".
>
> It would be very different from mainstream programming languages,
> however. And ideally you would want it to integrate with a lot of other
> infrastructure. So that alone might make it a non-starter, even if it
> was really good (which realistically early iterations wouldn't be).
>

There are special-purpose languages like Scratch which are not simple
text in that form. My Twitch channel bot has a command executor whose
language, if you call it that, is basically JSON - and the way to edit
those commands is very Scratch-inspired. These are not general-purpose
programming languages, but for what they do, they can be very useful.
It's a great way to put together incredibly high level primitives that
tie in well with the system they're in. (Imagine programming a model
train set, with primitives like "change the points here to go
straight" and "advance train #32 to the next red signal".)

I'm not sure how you'd make that useful for general-purpose
programming, but there's definitely a LOT of value in non-textual
languages for certain situations.

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


Re: for -- else: what was the motivation?

2022-10-18 Thread Peter J. Holzer
On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote:
> > which had special combinations for all the BASIC keywords). And if you
> > go this way, why not go a step further and dissociate the program from
> > its linear text representation? Add footnotes, different views,
> > hyperlinks, format mathematical expressions like formulas, etc.
> 
> http://literateprogramming.com/

Right. That's one of the inspirations for my comment.

But literate programming is of course still very much rooted in the
"linear text representation" paradigm. You have one definite source
which is a linear text.

In a world of IDEs, databases and hypertext that's probably not the best
we can do. As Raymond Hettinger would say, "there must be a better way".

It would be very different from mainstream programming languages,
however. And ideally you would want it to integrate with a lot of other
infrastructure. So that alone might make it a non-starter, even if it
was really good (which realistically early iterations wouldn't be).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-17 Thread Robert Latest via Python-list
 wrote:
> I had another crazy thought that I AM NOT ASKING anyone to do. OK?
>
> I was wondering about a sort of catch method you could use that generates a
> pseudo-signal only when the enclosed preceding  loop exits normally as a
> sort of way to handle the ELSE need without the use of a keyword known by
> the language. All you would need is an object of the right kind that is
> thrown and optionally caught.


(untested)

try:
while condition:
if not do_something():
raise RuntimeError
except RuntimeError:
pass
else:
print('Loop exited normally')

Ironically, this again relies on the much-used "else" and adds the overhead of
exception handling. Also from a natural language perspective I find the "try
...  except ... else" clause just as questionable as "while ... else." Since
we're discussing weird keywords: Maybe we can find another use for "finally."
In fact, one could argue that "while ... finally" could make just as much sense
as "while ... else" (but I won't).

> Of course, even if I fleshed this out and even if anyone thought it made
> sense, there is no such need now as Python has made a choice that meets the
> need even if few may dare use it or even know about it! LOL!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-17 Thread Dennis Lee Bieber
On Wed, 12 Oct 2022 23:19:39 +0100, Rob Cliffe 
declaimed the following:

>I too have occasionally used for ... else.  It does have its uses. But 
>oh, how I wish it had been called something else more meaningful, 
>whether 'nobreak' or whatever.  It used to really confuse me.  Now I've 

"expired"?


-- 
Wulfraed Dennis Lee Bieber AF6VN
wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Aw: Re: for -- else: what was the motivation?

2022-10-17 Thread Karsten Hilbert
> which had special combinations for all the BASIC keywords). And if you
> go this way, why not go a step further and dissociate the program from
> its linear text representation? Add footnotes, different views,
> hyperlinks, format mathematical expressions like formulas, etc.

http://literateprogramming.com/

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


Re: for -- else: what was the motivation?

2022-10-17 Thread Chris Angelico
On Mon, 17 Oct 2022 at 16:36, Antoon Pardon  wrote:
>
>
>
> Op 17/10/2022 om 04:01 schreef Chris Angelico:
> > On Mon, 17 Oct 2022 at 10:46,  wrote:
> >> My point Chris was that you can have a conversation where you are exploring
> >> and not proposing. Brainstorming, perhaps.
> > And my point is that either a proposal is a serious one that can
> > expect serious discussion, or it isn't. Yes, I'm aware that it wasn't
> > you who backpedalled as soon as any criticism was posted, but your
> > caveat comes to the same thing - if you're trying to avoid serious
> > criticism, you have to not post an idea.
>
> Your reaction was not serious criticisme but a belligerent reaction.
> You made it clear you wanted a fight. I choose not to enter that
> fight.
>

Well, if reacting strongly to a proposal to break LITERALLY EVERY
PYTHON PROGRAM EVER counts as not a serious criticism but a
belligerent reaction, then there's not really a lot of point
discussing further.

Bye.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon




Op 17/10/2022 om 04:01 schreef Chris Angelico:

On Mon, 17 Oct 2022 at 10:46,  wrote:

My point Chris was that you can have a conversation where you are exploring
and not proposing. Brainstorming, perhaps.

And my point is that either a proposal is a serious one that can
expect serious discussion, or it isn't. Yes, I'm aware that it wasn't
you who backpedalled as soon as any criticism was posted, but your
caveat comes to the same thing - if you're trying to avoid serious
criticism, you have to not post an idea.


Your reaction was not serious criticisme but a belligerent reaction.
You made it clear you wanted a fight. I choose not to enter that
fight.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Chris Angelico
On Mon, 17 Oct 2022 at 10:46,  wrote:
>
> My point Chris was that you can have a conversation where you are exploring
> and not proposing. Brainstorming, perhaps.

And my point is that either a proposal is a serious one that can
expect serious discussion, or it isn't. Yes, I'm aware that it wasn't
you who backpedalled as soon as any criticism was posted, but your
caveat comes to the same thing - if you're trying to avoid serious
criticism, you have to not post an idea.

> So my POINT (and I repeat NOT a suggestion) is that I can IMAGINE ways to
> add a feature to a loop, such as an extra optional argument that is called
> if the loop exits from the bottom. The code you now put in the ELSE clause
> might have to be in the lambda or whatever. That may not be a good fit for
> Python.

If you're inventing a completely new language, you can do whatever you
like, but it's not very practical to discuss small features when
there's no language to discuss them in. So are you discussing this as
a Python feature, or just saying "hey, in a vacuum, we could do this",
which is vacuously true?

> What may aggravate you is that lots of people keep telling you that the ELSE
> on a loop feature is not intuitive to many, sometimes even after it is
> explained.

I know it's unintuitive. That doesn't stop it being useful.

> My suggestion is you should deal with that and not take it out on others.
> Live and let live.

That's unrelated. Sorry to disappoint you.

> This forum may be about Python but not exclusively. I personally often enjoy
> hearing how some other system does something similar, such as discussions on
> how and whether Python should allow an underscore in static numbers given
> other languages do so, not always identically. We can learn from such
> comparisons, for good and also for bad.

That's correct, but usually there's at least SOME context. And if none
is given, is it or is it not reasonable to assume that people are
talking about Python?

> But if it makes you happy, take me off this list! I have so many things I
> need to do and free up time for.

I'm not in a position to do that, and my point was to show how
ridiculous empty proposals are :)

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


RE: for -- else: what was the motivation?

2022-10-16 Thread avi.e.gross
My point Chris was that you can have a conversation where you are exploring
and not proposing. Brainstorming, perhaps.

I was saying that there are many ways to signal things and in some
hypothetical new language, it may be implemented in novel ways that do not
break anything.

I note languages like JavaScript seem to love passing functions or setting
event handlers that may only be activated under unusual conditions.

So my POINT (and I repeat NOT a suggestion) is that I can IMAGINE ways to
add a feature to a loop, such as an extra optional argument that is called
if the loop exits from the bottom. The code you now put in the ELSE clause
might have to be in the lambda or whatever. That may not be a good fit for
Python.

What may aggravate you is that lots of people keep telling you that the ELSE
on a loop feature is not intuitive to many, sometimes even after it is
explained.

My suggestion is you should deal with that and not take it out on others.
Live and let live.

My view remains that something has been added and is available and won't
likely be changed so use it as-is or ignore it. 

But if anyone wants to make their own language, they can feel free to design
around this any way they wish. If they design an object that encapsulates a
loop and then add attributes to the object that are guaranteed to tell you
how the loop ended and run some code if it is set there, fine. 

This forum may be about Python but not exclusively. I personally often enjoy
hearing how some other system does something similar, such as discussions on
how and whether Python should allow an underscore in static numbers given
other languages do so, not always identically. We can learn from such
comparisons, for good and also for bad.

I am NOT proposing we change anything about ELSE and that was not my point.
My point was that sometimes rather than reuse an existing keyword in the
language or create new reserved keywords, there can be many possible ways to
extend functionality.

I know of languages with multiple variations on loops that do not break
existing code. If your syntax is for (...) { ...} then if you add the
ability to place some identifier ONLY in the context involved then for XXX
(...) { ...} may mean some altered functionality while YYY in the same spot
means something else and the original form continues to do what it always
did.

So are XXX and YYY keywords or something else?

Again, I do not understand why people here get so touchy.

But if it makes you happy, take me off this list! I have so many things I
need to do and free up time for.




-Original Message-
From: Python-list  On
Behalf Of Chris Angelico
Sent: Sunday, October 16, 2022 6:56 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

On Mon, 17 Oct 2022 at 08:22,  wrote:
> I had another crazy thought that I AM NOT ASKING anyone to do. OK?
>

Here's another proposal: Let's ban you from this mailing list. Don't worry,
I AM NOT ASKING anyone to do it. OK?

Do you see how ridiculous and pointless it is to have proposals with that
kind of caveat?

Make serious proposals that we can discuss reasonably, don't make fake
proposals and hide behind a caveat.

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

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Chris Angelico
On Mon, 17 Oct 2022 at 08:22,  wrote:
> I had another crazy thought that I AM NOT ASKING anyone to do. OK?
>

Here's another proposal: Let's ban you from this mailing list. Don't
worry, I AM NOT ASKING anyone to do it. OK?

Do you see how ridiculous and pointless it is to have proposals with
that kind of caveat?

Make serious proposals that we can discuss reasonably, don't make fake
proposals and hide behind a caveat.

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


RE: for -- else: what was the motivation?

2022-10-16 Thread avi.e.gross
Realistically an idea about something new is easier to consider than
changing what you have.

Some newer languages may well be designed from the start in new ways and
Julia is an example of a language that allows a wide swath of UNICODE
characters to be used in identifiers. They also let you type them in even
using ASCII keyboards for some level of compatibility.

The original topic asked about the topic of re-using ELSE as a known keyword
in a context I and some others feel is a stretch. But the alterative could
be to add an ever increasing number of keywords to meet new needs.

I had another crazy thought that I AM NOT ASKING anyone to do. OK?

I was wondering about a sort of catch method you could use that generates a
pseudo-signal only when the enclosed preceding  loop exits normally as a
sort of way to handle the ELSE need without the use of a keyword known by
the language. All you would need is an object of the right kind that is
thrown and optionally caught.

Of course, even if I fleshed this out and even if anyone thought it made
sense, there is no such need now as Python has made a choice that meets the
need even if few may dare use it or even know about it! LOL!




-Original Message-
From: Python-list  On
Behalf Of Antoon Pardon
Sent: Sunday, October 16, 2022 1:38 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?



Op 16/10/2022 om 19:03 schreef Chris Angelico:
> On Mon, 17 Oct 2022 at 03:57, Antoon Pardon  wrote:
>>
>> Op 16/10/2022 om 17:05 schreef Chris Angelico:
>>> On Sun, 16 Oct 2022 at 22:47, Antoon Pardon
wrote:
>>>> Why would I need good luck? I expressed an idea and you didn't like it.
>>>> That won't affect my life in a meaningful way.
>>> Well, with that attitude, it's not going to affect anyone else's 
>>> life either, so go ahead, carry on.
>> What attitude? I just floated a little idea. It was not 
>> meant/expected to affect anyone else's life. So why do you react as if it
was?
>>
> You expressed an idea that you would like to see implemented in 
> Python, and part of that idea was that people would be *obliged* to 
> write their code using non-ASCII keywords. If that were to be 
> implemented, it absolutely WOULD affect many people's lives.

So what? I made it clear that was an if I didn't expect to happen.
An idea that doesn't happen will not affect anyone, whatever the
consequences tied to the idea.

>   So if
> you're saying that your idea was not meant to affect anyone else's 
> life, you are saying that you floated the idea fully intending for it 
> to be ignored, which makes me wonder why you posted it in the first 
> place.

People can find it interesting to discuss an idea, even if they think there
is no chance the idea will be carried out.

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

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Peter J. Holzer
On 2022-10-16 19:52:47 +0200, Antoon Pardon wrote:
> Op 16/10/2022 om 19:01 schreef Peter J. Holzer:
> > On 2022-10-16 12:17:39 +0200, Antoon Pardon wrote:
> > > Op 16/10/2022 om 00:50 schreefavi.e.gr...@gmail.com:
> > > > That might not easily solve this problem. But I wonder if reserving
> > > > some kind of prefix might help, so anything like extension.0nNoBreak
> > > > could be added to a loop as a final clause and be treated as a
> > > > non-key keyword of sorts.
> > > My idea would be to reserve different unicode blocks for the keywords and
> > > the identifiers. e.g. We could reserve the mathematical alphanumeric block
> > > for keywords and all other letters and numbers for identifiers. Doing so
> > > would allow extenting the keywords without breaking programs that already
> > > use that combination as an identifier.
> > Or you could go back to the old Algol idea of underlining keywords.
> > 
> > Both have the same problem, though: They make editing with an ordinary
> > text editor pretty much impossible. You need a language-aware IDE which
> > makes entering these characters or markups simple.
> 
> That is not true with my idea. The editor would just need to be able
> to work with unicode characters. Vim can work with 퐝퐞퐟 just as it can
> with def.

Yes, vim can. But can the user? And the user's system?

And vim isn't the only editor out there. So you need a system for every
editor some Python programmer might want to use. While most will
probably use a sufficiently powerful editor, some won't.

> In vim I can also define abbreviations so that whenever I type ^Bd vim
> wil insert 퐝퐞퐟 for me.

Which requires the user to define and type abbreviations. Which may be
hard if they can't enter the characters in the first place (Ok, that may
not be a problem as most users will probably just install a package from
the internet,)

The same does work with underlines:

d̲e̲f̲

although weirdly my terminal underlines the wrong characters (the one to
the right instead of the one to the left).

The pragmatic action would of course to define "def" as an abbreviation
for "퐝퐞퐟" (or "d̲e̲f̲"), but then what have you won?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-16 Thread Axy via Python-list


On 16/10/2022 18:43, Antoon Pardon wrote:

Op 16/10/2022 om 17:03 schreef Avi Gross:

Interesting idea, Anton.

I would be interested in hearing more detail on how it would work.

Although much of programming has been centered on the Latin alphabet 
and especially English, that may change. I can imagine a customized 
compiler or interpreter that uses key words in the local language 
instead of for or while or if or else or even import.


Please, please please... forget about that idea.

I know examples. They had no future, and have no future. Either RMS or 
ESR once have written in one of their book: "Please write in C". Same 
here: please speak in English.


Although, if you like that idea who can stop you? In such a case I vote 
for ภาษาไทย


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


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon



Op 16/10/2022 om 19:01 schreef Peter J. Holzer:

On 2022-10-16 12:17:39 +0200, Antoon Pardon wrote:

Op 16/10/2022 om 00:50 schreefavi.e.gr...@gmail.com:

That might not easily solve this problem. But I wonder if reserving
some kind of prefix might help, so anything like extension.0nNoBreak
could be added to a loop as a final clause and be treated as a
non-key keyword of sorts.

My idea would be to reserve different unicode blocks for the keywords and
the identifiers. e.g. We could reserve the mathematical alphanumeric block
for keywords and all other letters and numbers for identifiers. Doing so
would allow extenting the keywords without breaking programs that already
use that combination as an identifier.

Or you could go back to the old Algol idea of underlining keywords.

Both have the same problem, though: They make editing with an ordinary
text editor pretty much impossible. You need a language-aware IDE which
makes entering these characters or markups simple.


That is not true with my idea. The editor would just need to be able
to work with unicode characters. Vim can work with 퐝퐞퐟 just as it can
with def.

In vim I can also define abbreviations so that whenever I type ^Bd vim
wil insert 퐝퐞퐟 for me.

It may be useful to have an alternative keyboard definition ready to
easily insert these characters into the editor but ordinary editors
should already be able to treat these characters as any other unicode
character.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon

Op 16/10/2022 om 17:03 schreef Avi Gross:

Interesting idea, Anton.

I would be interested in hearing more detail on how it would work.

Although much of programming has been centered on the Latin alphabet 
and especially English, that may change. I can imagine a customized 
compiler or interpreter that uses key words in the local language 
instead of for or while or if or else or even import.


If a region of UNICODE was set aside, would it have to be as a sort of 
additional ALT or shift key for anything, or just English characters 
or would it be for abstract symbols that would be mapped to and from a 
long list of reserved key words that may vary by locale?


I think you are carrying my idea further than I intended. I was just 
thinking that instead of using U+0064 U+0065 U+0066 [beinf def] we could 
be using U+1D41D U+1D41E U+1D41F [being  퐝퐞퐟].


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


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon




Op 16/10/2022 om 19:03 schreef Chris Angelico:

On Mon, 17 Oct 2022 at 03:57, Antoon Pardon  wrote:


Op 16/10/2022 om 17:05 schreef Chris Angelico:

On Sun, 16 Oct 2022 at 22:47, Antoon Pardon   wrote:

Why would I need good luck? I expressed an idea and you didn't like it.
That won't affect my life in a meaningful way.

Well, with that attitude, it's not going to affect anyone else's life
either, so go ahead, carry on.

What attitude? I just floated a little idea. It was not meant/expected to
affect anyone else's life. So why do you react as if it was?


You expressed an idea that you would like to see implemented in
Python, and part of that idea was that people would be *obliged* to
write their code using non-ASCII keywords. If that were to be
implemented, it absolutely WOULD affect many people's lives.


So what? I made it clear that was an if I didn't expect to happen.
An idea that doesn't happen will not affect anyone, whatever the
consequences tied to the idea.


  So if
you're saying that your idea was not meant to affect anyone else's
life, you are saying that you floated the idea fully intending for it
to be ignored, which makes me wonder why you posted it in the first
place.


People can find it interesting to discuss an idea, even if they think
there is no chance the idea will be carried out.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread MRAB

On 2022-10-15 23:50, avi.e.gr...@gmail.com wrote:

This has been discussed so often precisely because I swear NO CHOICE of keyword 
would satisfy everybody! Most languages start with designated keywords and some 
reserve a few for later use. But then things can get frozen in place to avoid 
breaking existing programs or break older compilers/interpreters.

Some languages use techniques to extend themselves more harmlessly such as creating a 
singleton object that has content that can be regular data as in math.pi, or 
functions/methods or new ides like "Symbols" that allow all kinds of extensions 
to the language in a fairly harmless way as no older program would likely have used 
features that did not exist.

That might not easily solve this problem. But I wonder if reserving some kind 
of prefix might help, so anything like extension.0nNoBreak could be added to a 
loop as a final clause and be treated as a non-key keyword of sorts.


If you'd accept 2 words:

for child in tree.getroot():
if child.tag == 'server':
break
not break:
raise ValueError(f"server tag not found in {lfile}")


-Original Message-
From: Python-list  On 
Behalf Of Rob Cliffe via Python-list
Sent: Wednesday, October 12, 2022 6:20 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

I too have occasionally used for ... else.  It does have its uses. But oh, how I wish it had been 
called something else more meaningful, whether 'nobreak' or whatever.  It used to really confuse 
me.  Now I've learned to mentally replace "else" by "if nobreak", it confuses 
me a bit less.
Rob Cliffe

On 12/10/2022 22:11, Weatherby,Gerard wrote:

As did I.

tree = ET.parse(lfile)
 for child in tree.getroot():
 if child.tag == 'server':
 break
 else:
 raise ValueError(f"server tag not found in {lfile}")

I think there are other places I could be using it, but honestly I tend to 
forget it’s available.

From: Python-list  
on behalf of Stefan Ram 

Date: Wednesday, October 12, 2022 at 2:22 PM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, 
opening attachments or clicking on links. ***


Axy  writes:
So, seriously, why they needed else if the following pieces produce 
same result? Does anyone know or remember their motivation?

   Just wrote code wherein I used "else"! This:

import locale
for name in( 'de', 'de_DE', 'deu_deu', 'deu', 'German', 'Deutsch' ):
 try: locale.setlocale( locale.LC_ALL, name ); break
 except locale.Error: pass
else: print( "Programm kann deutsche Schreibweise nicht einrichten." )

   .



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


Re: for -- else: what was the motivation?

2022-10-16 Thread Chris Angelico
On Mon, 17 Oct 2022 at 03:57, Antoon Pardon  wrote:
>
>
> Op 16/10/2022 om 17:05 schreef Chris Angelico:
> > On Sun, 16 Oct 2022 at 22:47, Antoon Pardon  wrote:
> >> Why would I need good luck? I expressed an idea and you didn't like it.
> >> That won't affect my life in a meaningful way.
> > Well, with that attitude, it's not going to affect anyone else's life
> > either, so go ahead, carry on.
>
> What attitude? I just floated a little idea. It was not meant/expected to
> affect anyone else's life. So why do you react as if it was?
>

You expressed an idea that you would like to see implemented in
Python, and part of that idea was that people would be *obliged* to
write their code using non-ASCII keywords. If that were to be
implemented, it absolutely WOULD affect many people's lives. So if
you're saying that your idea was not meant to affect anyone else's
life, you are saying that you floated the idea fully intending for it
to be ignored, which makes me wonder why you posted it in the first
place.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Peter J. Holzer
On 2022-10-16 12:17:39 +0200, Antoon Pardon wrote:
> Op 16/10/2022 om 00:50 schreef avi.e.gr...@gmail.com:
> > That might not easily solve this problem. But I wonder if reserving
> > some kind of prefix might help, so anything like extension.0nNoBreak
> > could be added to a loop as a final clause and be treated as a
> > non-key keyword of sorts.
> 
> My idea would be to reserve different unicode blocks for the keywords and
> the identifiers. e.g. We could reserve the mathematical alphanumeric block
> for keywords and all other letters and numbers for identifiers. Doing so
> would allow extenting the keywords without breaking programs that already
> use that combination as an identifier.

Or you could go back to the old Algol idea of underlining keywords.

Both have the same problem, though: They make editing with an ordinary
text editor pretty much impossible. You need a language-aware IDE which
makes entering these characters or markups simple. Maybe even a
specialized keyboard like they had for APL (or the Sinclair ZX computers
which had special combinations for all the BASIC keywords). And if you
go this way, why not go a step further and dissociate the program from
its linear text representation? Add footnotes, different views,
hyperlinks, format mathematical expressions like formulas, etc.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon



Op 16/10/2022 om 17:05 schreef Chris Angelico:

On Sun, 16 Oct 2022 at 22:47, Antoon Pardon  wrote:

Why would I need good luck? I expressed an idea and you didn't like it.
That won't affect my life in a meaningful way.

Well, with that attitude, it's not going to affect anyone else's life
either, so go ahead, carry on.


What attitude? I just floated a little idea. It was not meant/expected to
affect anyone else's life. So why do you react as if it was?

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Chris Angelico
On Sun, 16 Oct 2022 at 22:47, Antoon Pardon  wrote:
>
>
>
> Op 16/10/2022 om 13:03 schreef Chris Angelico:
> > On Sun, 16 Oct 2022 at 21:19, Antoon Pardon  wrote:
> >
> >> My idea would be to reserve different unicode blocks for the keywords
> >> and the identifiers. e.g. We could reserve the mathematical alphanumeric
> >> block for keywords and all other letters and numbers for identifiers.
> >> Doing so would allow extenting the keywords without breaking programs
> >> that already use that combination as an identifier.
> > Python currently defines identifiers as follows:
> > https://docs.python.org/3/reference/lexical_analysis.html#identifiers
> >
> > Briefly, what it means is that (aside from some backward compatibility
> > special cases) an identifier contains letters, numbers, and connector
> > punctuation, and must not start with a number. It's not by blocks,
> > it's by types.
> >
> > It's way WAY too late to change what's allowed for identifiers, as you
> > will potentially be breaking programs that use the current rules.
>
> So? Python has broken backward compatibility before. The cost could
> be acceptable. How many programs do you estimated use the mathematical
> alphanumeric block for an identifier at this moment?

> Why would I need good luck? I expressed an idea and you didn't like it.
> That won't affect my life in a meaningful way.

Well, with that attitude, it's not going to affect anyone else's life
either, so go ahead, carry on.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Avi Gross
Interesting idea, Anton.

I would be interested in hearing more detail on how it would work.

Although much of programming has been centered on the Latin alphabet and
especially English, that may change. I can imagine a customized compiler or
interpreter that uses key words in the local language instead of for or
while or if or else or even import.

If a region of UNICODE was set aside, would it have to be as a sort of
additional ALT or shift key for anything, or just English characters or
would it be for abstract symbols that would be mapped to and from a long
list of reserved key words that may vary by locale?

A serious problem I have been noting is the interactions between
typographical paradigms never expected to interact. I mean special
characters allowed or expected that clash. An example in Python and many
other languages is regular expressions. When using a string of characters,
you may have to deal with the rules for evaluating a string of that type
and double up backslash characters or be carefully as a dollar sign or
curly brace might invoke a side effect and interpolate something into it.
But for languages that allow RE to be entered without a string as in /.../
you have to write it differently.

I noted other ways in which naming conventions and even sort of keywords
need special care. Consider a Javascript program in a browser that can read
and manipulate HTML and CSS. The rules for names in JS do not allow hyphens
while others often do. So the programmers making the structures in the DOM
had to twist things. To access something like font-type you ask for font
Type as an example by changing the identifier to camel case.

I sometimes have programs that combine R and Python somewhat
interchangeably and it highlights places the naming does not match. R
allows periods as parts of names as in my.data and almost anything
including spaces if you use grave accent quotes such as `one [identifier`
so it is perfectly valid to have a function call like `[`(x, 5) to mean
x[5] albeit explaining why that is useful is beyond the scope. Similarly
you can make all kinds of in-line functions between percent signs as in %*%
or %specialized computation% and you sort of make your own keywords albeit
Chris and others may rightly suggest they are something else rather than
the first level of syntax.

My point is that your idea may need to support keywords for disparate ideas
and languages.

On Sun, Oct 16, 2022, 6:20 AM Antoon Pardon  wrote:

> Op 16/10/2022 om 00:50 schreef avi.e.gr...@gmail.com:
> > This has been discussed so often precisely because I swear NO CHOICE of
> keyword would satisfy everybody! Most languages start with designated
> keywords and some reserve a few for later use. But then things can get
> frozen in place to avoid breaking existing programs or break older
> compilers/interpreters.
> >
> > Some languages use techniques to extend themselves more harmlessly such
> as creating a singleton object that has content that can be regular data as
> in math.pi, or functions/methods or new ides like "Symbols" that allow all
> kinds of extensions to the language in a fairly harmless way as no older
> program would likely have used features that did not exist.
> >
> > That might not easily solve this problem. But I wonder if reserving some
> kind of prefix might help, so anything like extension.0nNoBreak could be
> added to a loop as a final clause and be treated as a non-key keyword of
> sorts.
>
> My idea would be to reserve different unicode blocks for the keywords
> and the identifiers. e.g. We could reserve the mathematical alphanumeric
> block for keywords and all other letters and numbers for identifiers.
> Doing so would allow extenting the keywords without breaking programs
> that already use that combination as an identifier.
>
> Python could slowly transition in this direction by first allowing the
> current keywords to be in this block. Every new keyword would only be in
> that unicode block. If would then be possible to write python code with
> this convention but it wouldn't be obligatory. After some time the
> python developers could decide to make it obligatory.
>
> I doubt this will idea will get from the ground, but I think it would
> allow for a smoother transition into new concepts, as it is no longer a
> strugle searching for a keyword that will break as little programs as
> possible.
>
> --
> Antoon Pardon.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon




Op 16/10/2022 om 13:03 schreef Chris Angelico:

On Sun, 16 Oct 2022 at 21:19, Antoon Pardon  wrote:


My idea would be to reserve different unicode blocks for the keywords
and the identifiers. e.g. We could reserve the mathematical alphanumeric
block for keywords and all other letters and numbers for identifiers.
Doing so would allow extenting the keywords without breaking programs
that already use that combination as an identifier.

Python currently defines identifiers as follows:
https://docs.python.org/3/reference/lexical_analysis.html#identifiers

Briefly, what it means is that (aside from some backward compatibility
special cases) an identifier contains letters, numbers, and connector
punctuation, and must not start with a number. It's not by blocks,
it's by types.

It's way WAY too late to change what's allowed for identifiers, as you
will potentially be breaking programs that use the current rules.


So? Python has broken backward compatibility before. The cost could
be acceptable. How many programs do you estimated use the mathematical
alphanumeric block for an identifier at this moment?


Python could slowly transition in this direction by first allowing the
current keywords to be in this block. Every new keyword would only be in
that unicode block. If would then be possible to write python code with
this convention but it wouldn't be obligatory. After some time the
python developers could decide to make it obligatory.

Obligatory??? Please explain how you intend to convince the entire
world that non-ASCII code is an acceptable requirement. Explain to me
how you're going to go to every text editor and ensure that it
supports easy entry of Python keywords that aren't ASCII. And please
explain how this is even better.


Why should I do that? It seems you have already made your mind up.
That is fine. It just makes explaining not very senseful.


I doubt this will idea will get from the ground, but I think it would
allow for a smoother transition into new concepts, as it is no longer a
strugle searching for a keyword that will break as little programs as
possible.

Yeah it won't. Good luck though.


Why would I need good luck? I expressed an idea and you didn't like it.
That won't affect my life in a meaningful way.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Chris Angelico
On Sun, 16 Oct 2022 at 21:19, Antoon Pardon  wrote:
>
> Op 16/10/2022 om 00:50 schreef avi.e.gr...@gmail.com:
> > This has been discussed so often precisely because I swear NO CHOICE of 
> > keyword would satisfy everybody! Most languages start with designated 
> > keywords and some reserve a few for later use. But then things can get 
> > frozen in place to avoid breaking existing programs or break older 
> > compilers/interpreters.
> >
> > Some languages use techniques to extend themselves more harmlessly such as 
> > creating a singleton object that has content that can be regular data as in 
> > math.pi, or functions/methods or new ides like "Symbols" that allow all 
> > kinds of extensions to the language in a fairly harmless way as no older 
> > program would likely have used features that did not exist.
> >
> > That might not easily solve this problem. But I wonder if reserving some 
> > kind of prefix might help, so anything like extension.0nNoBreak could be 
> > added to a loop as a final clause and be treated as a non-key keyword of 
> > sorts.
>
> My idea would be to reserve different unicode blocks for the keywords
> and the identifiers. e.g. We could reserve the mathematical alphanumeric
> block for keywords and all other letters and numbers for identifiers.
> Doing so would allow extenting the keywords without breaking programs
> that already use that combination as an identifier.

Python currently defines identifiers as follows:
https://docs.python.org/3/reference/lexical_analysis.html#identifiers

Briefly, what it means is that (aside from some backward compatibility
special cases) an identifier contains letters, numbers, and connector
punctuation, and must not start with a number. It's not by blocks,
it's by types.

It's way WAY too late to change what's allowed for identifiers, as you
will potentially be breaking programs that use the current rules.

> Python could slowly transition in this direction by first allowing the
> current keywords to be in this block. Every new keyword would only be in
> that unicode block. If would then be possible to write python code with
> this convention but it wouldn't be obligatory. After some time the
> python developers could decide to make it obligatory.

Obligatory??? Please explain how you intend to convince the entire
world that non-ASCII code is an acceptable requirement. Explain to me
how you're going to go to every text editor and ensure that it
supports easy entry of Python keywords that aren't ASCII. And please
explain how this is even better.

> I doubt this will idea will get from the ground, but I think it would
> allow for a smoother transition into new concepts, as it is no longer a
> strugle searching for a keyword that will break as little programs as
> possible.

Yeah it won't. Good luck though.

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


Re: for -- else: what was the motivation?

2022-10-16 Thread Antoon Pardon

Op 16/10/2022 om 00:50 schreef avi.e.gr...@gmail.com:

This has been discussed so often precisely because I swear NO CHOICE of keyword 
would satisfy everybody! Most languages start with designated keywords and some 
reserve a few for later use. But then things can get frozen in place to avoid 
breaking existing programs or break older compilers/interpreters.

Some languages use techniques to extend themselves more harmlessly such as creating a 
singleton object that has content that can be regular data as in math.pi, or 
functions/methods or new ides like "Symbols" that allow all kinds of extensions 
to the language in a fairly harmless way as no older program would likely have used 
features that did not exist.

That might not easily solve this problem. But I wonder if reserving some kind 
of prefix might help, so anything like extension.0nNoBreak could be added to a 
loop as a final clause and be treated as a non-key keyword of sorts.


My idea would be to reserve different unicode blocks for the keywords 
and the identifiers. e.g. We could reserve the mathematical alphanumeric 
block for keywords and all other letters and numbers for identifiers. 
Doing so would allow extenting the keywords without breaking programs 
that already use that combination as an identifier.


Python could slowly transition in this direction by first allowing the 
current keywords to be in this block. Every new keyword would only be in 
that unicode block. If would then be possible to write python code with 
this convention but it wouldn't be obligatory. After some time the 
python developers could decide to make it obligatory.


I doubt this will idea will get from the ground, but I think it would 
allow for a smoother transition into new concepts, as it is no longer a 
strugle searching for a keyword that will break as little programs as 
possible.


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


RE: for -- else: what was the motivation?

2022-10-15 Thread avi.e.gross
This has been discussed so often precisely because I swear NO CHOICE of keyword 
would satisfy everybody! Most languages start with designated keywords and some 
reserve a few for later use. But then things can get frozen in place to avoid 
breaking existing programs or break older compilers/interpreters.

Some languages use techniques to extend themselves more harmlessly such as 
creating a singleton object that has content that can be regular data as in 
math.pi, or functions/methods or new ides like "Symbols" that allow all kinds 
of extensions to the language in a fairly harmless way as no older program 
would likely have used features that did not exist.

That might not easily solve this problem. But I wonder if reserving some kind 
of prefix might help, so anything like extension.0nNoBreak could be added to a 
loop as a final clause and be treated as a non-key keyword of sorts.

-Original Message-
From: Python-list  On 
Behalf Of Rob Cliffe via Python-list
Sent: Wednesday, October 12, 2022 6:20 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

I too have occasionally used for ... else.  It does have its uses. But oh, how 
I wish it had been called something else more meaningful, whether 'nobreak' or 
whatever.  It used to really confuse me.  Now I've learned to mentally replace 
"else" by "if nobreak", it confuses me a bit less.
Rob Cliffe

On 12/10/2022 22:11, Weatherby,Gerard wrote:
> As did I.
>
> tree = ET.parse(lfile)
>  for child in tree.getroot():
>  if child.tag == 'server':
>  break
>  else:
>  raise ValueError(f"server tag not found in {lfile}")
>
> I think there are other places I could be using it, but honestly I tend to 
> forget it’s available.
>
> From: Python-list  
> on behalf of Stefan Ram 
> Date: Wednesday, October 12, 2022 at 2:22 PM
> To: python-list@python.org 
> Subject: Re: for -- else: what was the motivation?
> *** Attention: This is an external email. Use caution responding, 
> opening attachments or clicking on links. ***
>
> Axy  writes:
>> So, seriously, why they needed else if the following pieces produce 
>> same result? Does anyone know or remember their motivation?
>Just wrote code wherein I used "else"! This:
>
> import locale
> for name in( 'de', 'de_DE', 'deu_deu', 'deu', 'German', 'Deutsch' ):
>  try: locale.setlocale( locale.LC_ALL, name ); break
>  except locale.Error: pass
> else: print( "Programm kann deutsche Schreibweise nicht einrichten." )
>
>.
>
>
> --
> https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/p
> ython-list__;!!Cn_UX_p3!iyDac-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEd
> R04mSQ5Ln0OA1ETUNloyH24iY9meNHVdixLgWRYL8$<https://urldefense.com/v3/_
> _https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iyDa
> c-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEdR04mSQ5Ln0OA1ETUNloyH24iY9me
> NHVdixLgWRYL8$>

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

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


Re: for -- else: what was the motivation?

2022-10-15 Thread Grant Edwards
On 2022-10-12, Rob Cliffe via Python-list  wrote:
> I too have occasionally used for ... else.  It does have its uses. But 
> oh, how I wish it had been called something else more meaningful, 
> whether 'nobreak' or whatever.

I use it a few times year. I have to look it up in the documentation
every single time I do, and I always add a comment in the "else"
clause stating whether the looped completed "normally" or not.

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


Re: for -- else: what was the motivation?

2022-10-14 Thread Rob Cliffe via Python-list
I too have occasionally used for ... else.  It does have its uses. But 
oh, how I wish it had been called something else more meaningful, 
whether 'nobreak' or whatever.  It used to really confuse me.  Now I've 
learned to mentally replace "else" by "if nobreak", it confuses me a bit 
less.

Rob Cliffe

On 12/10/2022 22:11, Weatherby,Gerard wrote:

As did I.

tree = ET.parse(lfile)
 for child in tree.getroot():
 if child.tag == 'server':
 break
 else:
 raise ValueError(f"server tag not found in {lfile}")

I think there are other places I could be using it, but honestly I tend to 
forget it’s available.

From: Python-list  on behalf of 
Stefan Ram 
Date: Wednesday, October 12, 2022 at 2:22 PM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Axy  writes:

So, seriously, why they needed else if the following pieces produce same
result? Does anyone know or remember their motivation?

   Just wrote code wherein I used "else"! This:

import locale
for name in( 'de', 'de_DE', 'deu_deu', 'deu', 'German', 'Deutsch' ):
 try: locale.setlocale( locale.LC_ALL, name ); break
 except locale.Error: pass
else: print( "Programm kann deutsche Schreibweise nicht einrichten." )

   .


--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iyDac-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEdR04mSQ5Ln0OA1ETUNloyH24iY9meNHVdixLgWRYL8$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iyDac-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEdR04mSQ5Ln0OA1ETUNloyH24iY9meNHVdixLgWRYL8$>


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


Re: for -- else: what was the motivation?

2022-10-12 Thread dn




On 11/10/2022 02.13, Grant Edwards wrote:

On 2022-10-10, Chris Angelico  wrote:

On Mon, 10 Oct 2022 at 11:52, MRAB  wrote:


On 2022-10-10 00:40, dn wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
 wrote:


"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did
for others.


I've followed that advice for several decades. I find it much easier
to read code that's organized that way -- particularly when the
difference in block sizes is large (e.g. the first block is one line,
and the second is a a hundred).


Makes sense. Keep the 'cause' and 'effect' close together. In other 
words, making it easy to look 'up' from one of the 'suites' to see the 
if-statement/condition which directs that logic-branch.



Contrarily, (see @Karsten, earlier) the preference to bundle the 
"hundred" into one or more functions, rather than present as a 'wall of 
text'. Added advantage: well-chosen function names(!) will remind the 
reader of the purposes(!) of the "hundred".


Once both suites are short[ened], visibility improves (readability), and 
the above contention goes-away. Thus the sense of the condition becomes 
the most worthy consideration.


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-12 Thread Peter J. Holzer
On 2022-10-10 16:48:04 +, Robert Latest via Python-list wrote:
> Axy wrote:
> >> Also not really a justification for "shortest block first". Wanting
> >> some elaboration on that. What's the value in it?
> >
> > Well, the value is productivity. No need to save puzzles "what this 
> > hanging else belongs to?"
> 
> If you find yourself asking that question, the if-block is probably too long 
> to
> begin with.

ACK.


> > Code small things first and return early, same 

> > as taking a test: do easy and quick things first and boring and 
> > difficult ones later.
> 
> Yes, but in that case you have a very long indented "else" block,

If you return you don't have to indent the rest.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-12 Thread Peter J. Holzer
On 2022-10-10 10:11:10 +, Stefan Ram wrote:
>   I would not use tabs in source code as they are not
>   displayed in the same way everywhere.

Some would argue that this is a feature. Different people prefer
different indentation widths. Using a single tab character for an
indentation level allows everybody to view the file in their preferred
layout.

I have, however, found out that this requires more discipline than I and
the people I work with can muster. There is always someone who
accidentally converts some tabs to spaces, messing up indentation for
everyone else. So I require a "indent by x spaces" rule for all projects
I work on (unless the language convention have a strong preference for
tabs, like in Go).

In email I would always use spaces. Tabs are just too unreliable there.


>   Functions also come at a cost. From the Web:
   
Ah yes. Your infamous aversion against useful citations strikes again.

For those too lazy to use a search engine, the excerpt seems to be from
https://softwarebyscience.com/very-short-functions-are-a-code-smell-an-overview-of-the-science-on-function-length/

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-12 Thread Weatherby,Gerard
As did I.

tree = ET.parse(lfile)
for child in tree.getroot():
if child.tag == 'server':
break
else:
raise ValueError(f"server tag not found in {lfile}")

I think there are other places I could be using it, but honestly I tend to 
forget it’s available.

From: Python-list  on 
behalf of Stefan Ram 
Date: Wednesday, October 12, 2022 at 2:22 PM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Axy  writes:
>So, seriously, why they needed else if the following pieces produce same
>result? Does anyone know or remember their motivation?

  Just wrote code wherein I used "else"! This:

import locale
for name in( 'de', 'de_DE', 'deu_deu', 'deu', 'German', 'Deutsch' ):
try: locale.setlocale( locale.LC_ALL, name ); break
except locale.Error: pass
else: print( "Programm kann deutsche Schreibweise nicht einrichten." )

  .


--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iyDac-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEdR04mSQ5Ln0OA1ETUNloyH24iY9meNHVdixLgWRYL8$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iyDac-XjNlj78G0XwNzZ-FEHyuCZIy33n3cI9MUDM_FnEdR04mSQ5Ln0OA1ETUNloyH24iY9meNHVdixLgWRYL8$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-11 Thread Axy via Python-list



On 10/10/2022 06:15, avi.e.gr...@gmail.com wrote:

Chris, a short(er) answer to your addition below.

I did not at first share your perception but maybe do now. If the argument
was that ELSE and other constructs like FINALLY or CATCH are horrible
because they follow other code and important things should be first, that is
a silly argument.


You know, sometimes I'm of the same opinion, especially looking at 
"defer" efforts in Go.


However, I wouldn't judge that in terms of mental capabilities. Every 
construct has some initial rationale but sometimes even best practices 
eventually become notorious. There are many point of views to every 
feature but in general features aren't divine and worth revising even 
this looks disparaging.


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


Re: for -- else: what was the motivation?

2022-10-11 Thread Grant Edwards
On 2022-10-11,   wrote:

> But is that native python or some extension where "|" has been modified to
> mean something other than a form of OR in some places?

The latter.

> What module do you need to load to make that happen?

The provided link is for a page that shows the module and explains the
usage.



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


Re: for -- else: what was the motivation?

2022-10-11 Thread dn

On 10/10/2022 16.19, avi.e.gr...@gmail.com wrote:

I won't reply to everything Dave says and especially not the parts I fully 
agree with.

I think in many situations in life there is no ONE way to do things so most 
advice is heuristic at best and many exceptions may exist depending on your 
chosen approach. As such, I do not really think in PYTHON when writing code but 
an amalgam of many languages with all kinds of ways of doing things and then 
zoom in on how to do it in the current language be it Python or R or JavaScript 
and so on. Yes, I am in some sense focused but also open, just as in Human 
languages I may mostly be thinking in English but also sometimes see words and 
phrases pop into my mind from other languages that mean about the same thing 
and then filter it out to focus on whichever language I am supposed to be using 
at the time.


Given that we can both remember programming last-century, this 
surprised. (or may have misunderstood!)



If we think, in German, of some parting words for an older friend 
departing on a long trip, and translate word-for-word into English we 
might come out with: "May God pickle you".


There is a second step, which is to examine the 'solution' in terms of 
its expression (how the communication will be received), and thus the 
more-correct English expression would be: "May God preserve you"!


The two p-words are sufficiently-similar in meaning to appear 
synonymous, when examined in-isolation. However, that first expression 
would at least bemuse an (only) English-speaker, and quite possibly confuse!



One of the problems which 'appeared' when programmers were first given 
direct-access to the computer, eg time-sharing mini-computers; and which 
persists to this day, is "the rush to code". Indeed there are (still) 
some 'managers' who think that unless a programmer is writing code (s)he 
isn't 'working' - but we're only interested in our own behavior.


Accordingly, "design" and "development".

Back-when, some lecturers insisted that we first create a flow-chart or 
a pseudo-code solution for an assignment - BEFORE we coded in COBOL, 
FORTRAN, or whatever. In many ways, because we were learning the 
programming-language, most felt it very difficult to draw a flow-chart 
that didn't merely look like FORTRAN.
(to make that worse (for ourselves) I suspect many of us performed the 
latter first, and then ...) Many of us will have felt this some sort of 
academic-exercise or even 'a nuisance', but there was 'method in their 
madness'!



Relating back to the comment (above): when *designing* a 
solution/flow-charting/pseudo-code, an "amalgam" of programming 
constructs and human-language expressions will indeed add richness, 
opportunity, and alternatives. All serving to amplify analytic and 
design skill.


Conversely, when *coding*, the skill comes from employing the (specific, 
programming) language to best advantage. At which time, one's 
JS-knowledge is almost irrelevant, because the task is to convert a 
design outline or planned-solution, into Python.

(idiomatic, pythonic, efficient, readable, ...)
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


RE: for -- else: what was the motivation?

2022-10-11 Thread avi.e.gross
lates the first million primes
and feeds them in a pipeline that perhaps quits after seeing the first few
dozen, may look similar but wastes lots of resources in computing too much
and storing too much. And it fails if the program turns out to need more
than a million. 

The map and filter and reduce methods often call a function repeatedly on
data and combine the results. But if you use a generator, calling it
repeatedly is more like continuing the existing instance that is just
hibernating and can have very different results. Similarly, languages that
are vectorized may do better to not be called through these functions as
they can perform the many operations on their own on known data of a known
length. But they can often be easy to pipeline in various ways with other
such vectorized functions somewhat more directly.

This forum often talks about what methods seem more "pythonic" than others.
Arguably generators are now part of a pythonic way for many. Not sure if
various ideas of "pipelines" are equally pythonic and some may really be
rather foreign to many programmers, at least until they catch on.

Avi


-Original Message-
From: Python-list  On
Behalf Of Antoon Pardon
Sent: Tuesday, October 11, 2022 10:30 AM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?



Op 10/10/2022 om 04:38 schreef avi.e.gr...@gmail.com:
> [This is an answer for Peter and can easily be skipped by those who 
> know or have no wish to.]
>
> Strictly speaking Peter, the word "pipe" may not mean quite something 
> in Python but other concepts like chaining may be better.
>
> The original use of the word I am used to was at the UNIX shell level 
> where an in-core data structure called a pipe was used to connect the 
> output of one process to the inputr of another, sometimes in long chains
like:
>
>   cat file1 file2 file3 | grep pattern | ... | lp

Something like that can be done in python with the same kind of syntax:

https://code.activestate.com/recipes/580625-collection-pipeline-in-python/

I have my own python3 module with stuff like that and I find it very
usefull.

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

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


Re: for -- else: what was the motivation?

2022-10-11 Thread Antoon Pardon




Op 10/10/2022 om 04:38 schreef avi.e.gr...@gmail.com:

[This is an answer for Peter and can easily be skipped by those who know or
have no wish to.]

Strictly speaking Peter, the word "pipe" may not mean quite something in
Python but other concepts like chaining may be better.

The original use of the word I am used to was at the UNIX shell level where
an in-core data structure called a pipe was used to connect the output of
one process to the inputr of another, sometimes in long chains like:

  cat file1 file2 file3 | grep pattern | ... | lp


Something like that can be done in python with the same kind of syntax:

https://code.activestate.com/recipes/580625-collection-pipeline-in-python/

I have my own python3 module with stuff like that and I find it very usefull.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Michael F. Stemper

On 09/10/2022 15.02, Peter J. Holzer wrote:

On 2022-10-09 15:32:13 -0400, Avi Gross wrote:

and of course no pipelines.


Since you've now used that term repeatedly: What is a pipeline in
Python?


Could it be what's discussed starting on page 35 of this presentation?


--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Robert Latest via Python-list
Axy wrote:
>> Also not really a justification for "shortest block first". Wanting
>> some elaboration on that. What's the value in it?
>
> Well, the value is productivity. No need to save puzzles "what this 
> hanging else belongs to?"

If you find yourself asking that question, the if-block is probably too long to
begin with.

> Code small things first and return early, same 
> as taking a test: do easy and quick things first and boring and 
> difficult ones later.

Yes, but in that case you have a very long indented "else" block, and at the
point where the unindent happens you are scratching your head again like
before. Better to immediately return or break and not to use any "else" block
at all.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Chris Angelico
On Tue, 11 Oct 2022 at 08:55, Robert Latest via Python-list
 wrote:
>
> Chris Angelico wrote:
> > Yes, I'm aware that code readability becomes irrelevant for
> > short-duration projects. Beside the point. I'm wondering how important
> > it really is to have the shortest block first.
>
> I usually put the most expected / frequent / not negated block first if the
> whole if/else statement is not "too long". Sometimes whatever you want to do
> becomes pointless if a certain conditions is not met, in which case I do an
> early break or return and have no else block at all.
>
> > Given that for-else is an excellent, if rarely-used, construct
>
> I knew it existed but coming from C I never thought to exploit it. I know I
> wrote loops like this:
>
> found = None
> while not found:
> found = search(something)
> if found:
> break
> if not found:
> complain()
>
> Need to look into using "else" in these cases.

Yep, that's exactly what for-else is great at!

while True:
if search(something): break
else:
complain()

(although rather than a "while True", you're probably iterating over
things to search for, in some way)

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Robert Latest via Python-list
Grant Edwards wrote:
> I've followed that advice for several decades. I find it much easier
> to read code that's organized that way -- particularly when the
> difference in block sizes is large (e.g. the first block is one line,
> and the second is a a hundred).

If any conditionally executed blocks is a hundred lines, I believe your code
needs refactoring. I know mine does. Either the long block should go into an
extra function, or you do a "fail and bail" (just learned that phrase).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Jach Feng
Axy 在 2022年10月10日 星期一下午5:55:29 [UTC+8] 的信中寫道:
> On 09/10/2022 03:33, Jach Feng wrote: 
> > The else is always coming with the break, not the for. 
> However, the compiler does not complain. 
Sure, the compiler will not complain even in a IOCCC contest:-)

> > but the [for...else] is insane. 
> Not in Python. 
The confusion is always in human mind.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Robert Latest via Python-list
Chris Angelico wrote:
> Yes, I'm aware that code readability becomes irrelevant for
> short-duration projects. Beside the point. I'm wondering how important
> it really is to have the shortest block first.

I usually put the most expected / frequent / not negated block first if the
whole if/else statement is not "too long". Sometimes whatever you want to do
becomes pointless if a certain conditions is not met, in which case I do an
early break or return and have no else block at all.

> Given that for-else is an excellent, if rarely-used, construct

I knew it existed but coming from C I never thought to exploit it. I know I
wrote loops like this:

found = None
while not found:
found = search(something)
if found:
break
if not found:
complain()

Need to look into using "else" in these cases.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Jon Ribbens via Python-list
On 2022-10-10, Calvin Spealman  wrote:
> On Sat, Oct 8, 2022 at 5:35 PM rbowman  wrote:
>> On 10/7/22 21:32, Axy wrote:
>> > So, seriously, why they needed else if the following pieces produce same
>> > result? Does anyone know or remember their motivation?
>>
>> In real scenarios there would be more logic in the for block that would
>> meet a condition and break out of the loop. If the condition is never
>> met, the else block runs. To steal from w3schools:
>>
>>
>> fruits = ["apple", "peach", "cherry"]
>> for x in fruits:
>>print(x)
>>if x == "banana":
>>  break
>> else:
>>print("Yes we got no bananas")
>>
>
> I wonder if for/else could have been less confusing if it was referred to
> as for-break-else and if the else clause was only valid syntax if the for
> loop actually contained a break statement in the first place.

Watch out, I suggested that here some years ago and it was derided
as being an "arrogant and foolish" idea.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: for -- else: what was the motivation?

2022-10-10 Thread avi.e.gross
I just want to get clear on what may be a side issue

The suggestion is that a loop with an ELSE clause only makes sense if the
user can BREAK out without finishing, right?

My first question is whether a warning or even error makes sense if there is
no BREAK statement anywhere in the loop but there is another way to break
out such as a RETURN statement or perhaps from an error induced that is not
caught and then propagates outward?

Or is there some mechanism that would still run the ELSE clause in such
cases?

The second is to note some break statements are potentially never executed
such as: if False: break

There are actually scenarios where you can remain in a loop to the end and
not do anything rather than break, but of course in that case, the ELSE
clause running makes little sense to only run if you finish normally unless
it can use a shared Boolean variable you used to skip the rest of the loop
and use that to decide. That can be done easily enough without the ELSE, I
would think.



-Original Message-
From: Python-list  On
Behalf Of Weatherby,Gerard
Sent: Monday, October 10, 2022 2:25 PM
To: Axy ; python-list@python.org
Subject: Re: for -- else: what was the motivation?

pylint, at least, provides a warning:

fe.py:4:0: W0120: Else clause on loop without a break statement
(useless-else-on-loop)


sum = 0
for i in range(5):
sum += i
else:
print("Always executes")
print(sum)


From: Python-list  on
behalf of Axy via Python-list 
Date: Monday, October 10, 2022 at 1:10 PM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening
attachments or clicking on links. ***

> On 10/10/2022 15:52, Weatherby,Gerard wrote:
>> I wonder if for/else could have been less confusing if it was 
>> referred to as for-break-else and if the else clause was only valid 
>> syntax if the for loop actually contained a break statement in the 
>> first place.
>
> Sounds reasonable. It would be something alike UnboundLocalError when 
> a local variable referenced before assignment. If they won't remove 
> "else" completely in far future, that checking really worths 
> implementing now.

Actually, I think a warning would be sufficient, as in the following quick
prototype. If someone can implement this quickly in CPython, that would be
great (last time I hacked it, it was 2.4)

Axy.

import ast

tree = ast.parse('''
# sample code
a = 0
for i in 'asd':
 a += i
 while x:
 pass
 else:
 print('wow')
 break
 print(i)
else:
 print(0)
''', mode='exec')

def check_ast(node):
 if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
 if node.orelse and have_no_break(node.body):
 print(f'Warning: the loop at line {node.lineno} has no "break"
statement,'
   f' "else" clause at line {node.orelse[0].lineno} won\'t
run')
 else:
 for child in ast.iter_child_nodes(node):
 check_ast(child)

def have_no_break(loop_body):
 for node in loop_body:
 if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
 # nested loop
 check_ast(node)
 elif isinstance(node, ast.Break):
 return False
 elif isinstance(node, list):
 for child in ast.iter_child_nodes(node):
 if have_no_break(child) == False:
 return False
 return True


for node in tree.body:
 check_ast(node)
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-
list__;!!Cn_UX_p3!mlK4jRkfDC_akw-fIqWaMVf707GQsiyvj_sRHTsFnuG4ak5mKWwSavtz4n
jlBNIu1H0VHrR9gyjuQpxGqZ1dacU1Xw$<https://urldefense.com/v3/__https:/mail.py
thon.org/mailman/listinfo/python-list__;!!Cn_UX_p3!mlK4jRkfDC_akw-fIqWaMVf70
7GQsiyvj_sRHTsFnuG4ak5mKWwSavtz4njlBNIu1H0VHrR9gyjuQpxGqZ1dacU1Xw$>
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Peter J. Holzer
On 2022-10-09 22:38:28 -0400, avi.e.gr...@gmail.com wrote:
> [This is an answer for Peter and can easily be skipped by those who know or
> have no wish to.]
> 
> Strictly speaking Peter, the word "pipe" may not mean quite something in
> Python but other concepts like chaining may be better.
> 
> The original use of the word I am used to was at the UNIX shell level where
> an in-core data structure called a pipe was used

To paraphrase Mark Twain, the reports of Unix' death have been greatly
exaggerated.

Unix (or at least its bastard offsprings Linux and OSX) is alive and
well and still has pipes. I use them every day.


> If you have an object with some method you can call on it (or in some cases
> a normal function call) that returns  another (or the same) object, then you
> can write code like:
> 
> This.that.other

Yeah, I thought you might be referring to that. I've just never seen the
term "pipeline" for that construct (I think "method chaining" is
reasonably common).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Peter J. Holzer
On 2022-10-10 12:40:44 +1300, dn wrote:
> On 10/10/2022 05.56, Peter J. Holzer wrote:
> > On 2022-10-09 12:18:09 -0400, Avi Gross wrote:
> > > Some would argue for a rule related to efficiency of execution. When you
> > > have multiple blocks as in an if-else or case statement with multiple
> > > choices, that you order the most common cases first. Those shorten
> > > execution more often than the rarer cases especially the ones that should
> > > never happen.
> > 
> > Those of us who started programming on 8 bit homecomputers of course
> > have efficiency always at the back of their heads, but I find this
> 
> ... for mainframes just as much as micro-computers!

I knew this would be coming :-).

> Regarding execution-efficiencies, I'm sure @Avi knows better than I: It
> seems likely that Python, as an interpreted language, will create 'blocks'
> of its virtual-machine code in the same order as they appear in the
> Python-source. However, aren't there optimising compilers which do something
> intelligent with the equivalent clauses/suites in other languages?

They can certainly move the code around. So something like

if a:
long block a
elif b:
long block b
else:
long block c

could be compiled into (pseudo-python):

if a:
goto label_a
elif b:
goto label_b
long block c
goto end
label_a:
long block a
goto end
label_b:
long block b
end:
pass

If they can prove that it makes no difference they can also change the
order of checking conditions:

def f(a: int) -> str:
if a < 0:
return "negative"
elif a > 100:
return "big"
else:
return "meh"

could be compiled into the equivalent of:

def f(a: int) -> str:
if a > 100:
return "big"
elif a < 0:
return "negative"
else:
return "meh"

since an int cannot be simultaneously less then 0 and larger than 100.

But if the order does matter, as in

def f(a: bool, b: bool) -> int:
if a:
return 1
elif b:
return 2
else:
return 3

it can't do any transformations which would change the result.

(note that this is a point where it's really important what a language
does or does not guarantee)

> 
> Regardless, is a Jump-instruction which transfers else-control to a block
> five machine-instructions 'down', any less efficient than a jump which spans
> 50-instructions?

That depends on the CPU. Some CPUs have different jump instructions for
different sizes (for example, for a typical risc cpu the instruction and
the offset have to fit in a 32 bit word. So you would be limited to
direct jumps of plus or minus a few hundred megabytes. For longer jumps
you need to load the address into a register and jump indirectly. CISC
CPUs with variable length instructions may have finer distinctions.) A
very short jump may continue within the same cache line or maybe even on
an instruction which has already been decoded. A longer jump may have to
load the next instruction from RAM. Or a jump to the beginning of a
cache line may be faster than one to the middle. And then of course
there is branch prediction ...

So lots of variability there.


> > There is of course the opposite view that you should just get all of the
> > confounding factors out of the way first, so that the default is also
> > the common case. I also do that sometimes, but then I don't hide this in
> > in an else: clause but do something like this:
> > 
> > for item in whatever:
> >  if not_this_one(item):
> >  continue
> >  if neither_this_one(item):
> >  continue
> >  if cant_continue(item):
> >  break
> >  if oopsie():
> >  raise SomeError()
> > 
> >  do_something_with(item)
> >  and_some_more(item)
> >  we_are_done(item)
> > 
> > which shows visually what the main purpose of the loop (or function or
> > other block) is.
> 
> Nicely stated!
> 
> NB I've seen sufficient of @Peter's posts to know that this was never (even
> implied to be) intended as a snippet for all occasions!
> 
> 
> It also illustrates why such is less readable: because we have to scan four
> if-statements before we can 'see' the purpose of the loop. My 'itch' would
> be to extract this code 'out' to a function - that way the name will convey
> the somewhat-obscured purpose of the loop.
> 
> 
> Alternately, reduce the 'distractions':-
> 
> try:
> for item in whatever:
> inspect_the_data( item )
> do_something_with(item)
> and_some_more(item)
> we_are_done(item)
> except SomeError:
> ...
> except CustomBreakException:
> ... ?pass?# same effect as break
> 
> by 'hiding' in:
> 
> def inspect_the_data( item ):
> if not_this_one(item):
> continue

This doesn't work. You can't continue (or break) a loop in a calling
function. (I think it works (or 

Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list



On 10/10/2022 19:25, Weatherby,Gerard wrote:


pylint, at least, provides a warning:

fe.py:4:0: W0120: Else clause on loop without a break statement 
(useless-else-on-loop)



I'm using flake8, it does not, alas.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Weatherby,Gerard
pylint, at least, provides a warning:

fe.py:4:0: W0120: Else clause on loop without a break statement 
(useless-else-on-loop)


sum = 0
for i in range(5):
sum += i
else:
print("Always executes")
print(sum)


From: Python-list  on 
behalf of Axy via Python-list 
Date: Monday, October 10, 2022 at 1:10 PM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

> On 10/10/2022 15:52, Weatherby,Gerard wrote:
>> I wonder if for/else could have been less confusing if it was
>> referred to
>> as for-break-else and if the else clause was only valid syntax if the
>> for
>> loop actually contained a break statement in the first place.
>
> Sounds reasonable. It would be something alike UnboundLocalError when
> a local variable referenced before assignment. If they won't remove
> "else" completely in far future, that checking really worths
> implementing now.

Actually, I think a warning would be sufficient, as in the following
quick prototype. If someone can implement this quickly in CPython, that
would be great (last time I hacked it, it was 2.4)

Axy.

import ast

tree = ast.parse('''
# sample code
a = 0
for i in 'asd':
 a += i
 while x:
 pass
 else:
 print('wow')
 break
 print(i)
else:
 print(0)
''', mode='exec')

def check_ast(node):
 if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
 if node.orelse and have_no_break(node.body):
 print(f'Warning: the loop at line {node.lineno} has no
"break" statement,'
   f' "else" clause at line {node.orelse[0].lineno}
won\'t run')
 else:
 for child in ast.iter_child_nodes(node):
 check_ast(child)

def have_no_break(loop_body):
 for node in loop_body:
 if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
 # nested loop
 check_ast(node)
 elif isinstance(node, ast.Break):
 return False
 elif isinstance(node, list):
 for child in ast.iter_child_nodes(node):
 if have_no_break(child) == False:
 return False
 return True


for node in tree.body:
 check_ast(node)
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!mlK4jRkfDC_akw-fIqWaMVf707GQsiyvj_sRHTsFnuG4ak5mKWwSavtz4njlBNIu1H0VHrR9gyjuQpxGqZ1dacU1Xw$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!mlK4jRkfDC_akw-fIqWaMVf707GQsiyvj_sRHTsFnuG4ak5mKWwSavtz4njlBNIu1H0VHrR9gyjuQpxGqZ1dacU1Xw$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list



On 10/10/2022 15:52, Weatherby,Gerard wrote:
I wonder if for/else could have been less confusing if it was 
referred to
as for-break-else and if the else clause was only valid syntax if the 
for

loop actually contained a break statement in the first place.


Sounds reasonable. It would be something alike UnboundLocalError when 
a local variable referenced before assignment. If they won't remove 
"else" completely in far future, that checking really worths 
implementing now.


Actually, I think a warning would be sufficient, as in the following 
quick prototype. If someone can implement this quickly in CPython, that 
would be great (last time I hacked it, it was 2.4)


Axy.

import ast

tree = ast.parse('''
# sample code
a = 0
for i in 'asd':
    a += i
    while x:
    pass
    else:
    print('wow')
    break
    print(i)
else:
    print(0)
''', mode='exec')

def check_ast(node):
    if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
    if node.orelse and have_no_break(node.body):
    print(f'Warning: the loop at line {node.lineno} has no 
"break" statement,'
  f' "else" clause at line {node.orelse[0].lineno} 
won\'t run')

    else:
    for child in ast.iter_child_nodes(node):
    check_ast(child)

def have_no_break(loop_body):
    for node in loop_body:
    if isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
    # nested loop
    check_ast(node)
    elif isinstance(node, ast.Break):
    return False
    elif isinstance(node, list):
    for child in ast.iter_child_nodes(node):
    if have_no_break(child) == False:
    return False
    return True


for node in tree.body:
    check_ast(node)
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list


On 10/10/2022 15:52, Weatherby,Gerard wrote:

Core developer Raymond Hettinger explains the history starting at 15:40 
https://www.youtube.com/watch?v=OSGv2VnC0go

(which I found on stackoverflow 
https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops
 )

TL:DR
The “else” is a historical artificial from the way developers thought during 
the transition from unstructured (i.e. “GOTO”) programming to structured 
programming. Since we all do structured now, it seems odd.


From: Python-list  on behalf of 
Calvin Spealman 
Date: Monday, October 10, 2022 at 10:38 AM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

On Sat, Oct 8, 2022 at 5:35 PM rbowman  wrote:


On 10/7/22 21:32, Axy wrote:

So, seriously, why they needed else if the following pieces produce same
result? Does anyone know or remember their motivation?

In real scenarios there would be more logic in the for block that would
meet a condition and break out of the loop. If the condition is never
met, the else block runs. To steal from w3schools:


fruits = ["apple", "peach", "cherry"]
for x in fruits:
print(x)
if x == "banana":
  break
else:
print("Yes we got no bananas")


I wonder if for/else could have been less confusing if it was referred to
as for-break-else and if the else clause was only valid syntax if the for
loop actually contained a break statement in the first place.


Sounds reasonable. It would be something alike UnboundLocalError when a 
local variable referenced before assignment. If they won't remove "else" 
completely in far future, that checking really worths implementing now.


Excellent stackoverflow link, thanks!

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Weatherby,Gerard
Core developer Raymond Hettinger explains the history starting at 15:40 
https://www.youtube.com/watch?v=OSGv2VnC0go

(which I found on stackoverflow 
https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops
 )

TL:DR
The “else” is a historical artificial from the way developers thought during 
the transition from unstructured (i.e. “GOTO”) programming to structured 
programming. Since we all do structured now, it seems odd.


From: Python-list  on 
behalf of Calvin Spealman 
Date: Monday, October 10, 2022 at 10:38 AM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

On Sat, Oct 8, 2022 at 5:35 PM rbowman  wrote:

> On 10/7/22 21:32, Axy wrote:
> > So, seriously, why they needed else if the following pieces produce same
> > result? Does anyone know or remember their motivation?
>
> In real scenarios there would be more logic in the for block that would
> meet a condition and break out of the loop. If the condition is never
> met, the else block runs. To steal from w3schools:
>
>
> fruits = ["apple", "peach", "cherry"]
> for x in fruits:
>print(x)
>if x == "banana":
>  break
> else:
>print("Yes we got no bananas")
>

I wonder if for/else could have been less confusing if it was referred to
as for-break-else and if the else clause was only valid syntax if the for
loop actually contained a break statement in the first place.

--

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

calvin.speal...@redhat.com  M: +1.336.210.5107
[image: 
https://urldefense.com/v3/__https://red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$<https://urldefense.com/v3/__https:/red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$>
  ] 
<https://urldefense.com/v3/__https://red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$
  >
TRIED. TESTED. TRUSTED. 
<https://urldefense.com/v3/__https://redhat.com/trusted__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihjGGi9WT$
  >
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihnTgBbx-$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihnTgBbx-$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Calvin Spealman
On Sat, Oct 8, 2022 at 5:35 PM rbowman  wrote:

> On 10/7/22 21:32, Axy wrote:
> > So, seriously, why they needed else if the following pieces produce same
> > result? Does anyone know or remember their motivation?
>
> In real scenarios there would be more logic in the for block that would
> meet a condition and break out of the loop. If the condition is never
> met, the else block runs. To steal from w3schools:
>
>
> fruits = ["apple", "peach", "cherry"]
> for x in fruits:
>print(x)
>if x == "banana":
>  break
> else:
>print("Yes we got no bananas")
>

I wonder if for/else could have been less confusing if it was referred to
as for-break-else and if the else clause was only valid syntax if the for
loop actually contained a break statement in the first place.

-- 

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

calvin.speal...@redhat.com  M: +1.336.210.5107
[image: https://red.ht/sig] 
TRIED. TESTED. TRUSTED. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Weatherby,Gerard
try:
open(disk)
except:
error(“Can’t open disk”)
lots of things

From: Python-list  on 
behalf of Karsten Hilbert 
Date: Monday, October 10, 2022 at 5:46 AM
To: python-list@python.org 
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

Am Sun, Oct 09, 2022 at 09:58:14AM + schrieb Stefan Ram:

>   I often follow this rule. For me, it's about readability. Compare:
>
> if not open( disk ):
> error( "Can't open disk" )
> else:
> printf( "now imagine there's some larger block here" )
... ad infinitum 

Should this not be

if not open( disk ):
error( "Can't open disk" )
else:
do_lots_of_things_with(disk)

as for readability ?

Or even

if not open( disk ):
error( "Can't open disk" )
return what_needs_to_be_returned

do_lots_of_things_with(disk)

The latter version may need some code reorganization, though.

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!nWwvwKC2eetL3YQnTS4jDih5YRZ_ziu4gPuU73R7LDX8-Kq0bXR-h4E_0kJopk-ud2oeAq6NwvykTB40o82ris6pM1aC$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!nWwvwKC2eetL3YQnTS4jDih5YRZ_ziu4gPuU73R7LDX8-Kq0bXR-h4E_0kJopk-ud2oeAq6NwvykTB40o82ris6pM1aC$>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Grant Edwards
On 2022-10-10, Chris Angelico  wrote:
> On Mon, 10 Oct 2022 at 11:52, MRAB  wrote:
>>
>> On 2022-10-10 00:40, dn wrote:
>> > On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
>> >  wrote:
>> >
>> >> "shortest block first"
>> >
>> > Have never heard this advice before. Kind-of rankled with me, as it did
>> > for others.

I've followed that advice for several decades. I find it much easier
to read code that's organized that way -- particularly when the
difference in block sizes is large (e.g. the first block is one line,
and the second is a a hundred).

--
Grant

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Chris Angelico
On Mon, 10 Oct 2022 at 22:37, Axy via Python-list
 wrote:
>
>
> On 10/10/2022 12:24, Chris Angelico wrote:
> > On Mon, 10 Oct 2022 at 21:57, Axy via Python-list
> >  wrote:
> >>
> >>> Not sure what you mean, but a for-else without a break is quite
> >>> useless. What exactly ARE you arguing here?
> >>>
> >>> The else is associated with the break to the exact extent that one is
> >>> essential to the other's value.
> >> I'm not arguing. That was just for the record, how things are done in
> >> Python. Basically, I simply asked a question and got a definite answer
> >> and clear understanding shortly, in a few replies. All the rest of this
> >> thread looks irrelevant to me, it's about coding style and probably
> >> should be continued under a different title, but I'm not interested to
> >> participate in it.
> > Here's where the "rest of this thread" started:
> >
> >> Actually the reason I never used "else" was the violation of the rule of
> >> beauty "shortest block first".
> > You disparaged a feature on the basis of a style rule that few of us
> > had heard of or agree with.
> Oh, I'm really sorry. My apologies.
> >   We all agree that coding style is
> > important; none of us would see block length as a reason to avoid
> > using an else clause on a for loop.
>
> As I understand from the above there must be a committee that delegates
> a speaker? Where to read rules? How to participate? There's something
> beyond this list I'm not aware of yet?

We in this thread. Look at the past replies.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list



On 10/10/2022 12:24, Chris Angelico wrote:

On Mon, 10 Oct 2022 at 21:57, Axy via Python-list
 wrote:



Not sure what you mean, but a for-else without a break is quite
useless. What exactly ARE you arguing here?

The else is associated with the break to the exact extent that one is
essential to the other's value.

I'm not arguing. That was just for the record, how things are done in
Python. Basically, I simply asked a question and got a definite answer
and clear understanding shortly, in a few replies. All the rest of this
thread looks irrelevant to me, it's about coding style and probably
should be continued under a different title, but I'm not interested to
participate in it.

Here's where the "rest of this thread" started:


Actually the reason I never used "else" was the violation of the rule of
beauty "shortest block first".

You disparaged a feature on the basis of a style rule that few of us
had heard of or agree with.

Oh, I'm really sorry. My apologies.

  We all agree that coding style is
important; none of us would see block length as a reason to avoid
using an else clause on a for loop.


As I understand from the above there must be a committee that delegates 
a speaker? Where to read rules? How to participate? There's something 
beyond this list I'm not aware of yet?


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


Re: for -- else: what was the motivation?

2022-10-10 Thread Chris Angelico
On Mon, 10 Oct 2022 at 21:57, Axy via Python-list
 wrote:
>
>
> > Not sure what you mean, but a for-else without a break is quite
> > useless. What exactly ARE you arguing here?
> >
> > The else is associated with the break to the exact extent that one is
> > essential to the other's value.
>
> I'm not arguing. That was just for the record, how things are done in
> Python. Basically, I simply asked a question and got a definite answer
> and clear understanding shortly, in a few replies. All the rest of this
> thread looks irrelevant to me, it's about coding style and probably
> should be continued under a different title, but I'm not interested to
> participate in it.

Here's where the "rest of this thread" started:

> Actually the reason I never used "else" was the violation of the rule of
> beauty "shortest block first".

You disparaged a feature on the basis of a style rule that few of us
had heard of or agree with. We all agree that coding style is
important; none of us would see block length as a reason to avoid
using an else clause on a for loop.

Your subsequent posts have left me confused as to what you're trying to convey.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list




Not sure what you mean, but a for-else without a break is quite
useless. What exactly ARE you arguing here?

The else is associated with the break to the exact extent that one is
essential to the other's value.


I'm not arguing. That was just for the record, how things are done in 
Python. Basically, I simply asked a question and got a definite answer 
and clear understanding shortly, in a few replies. All the rest of this 
thread looks irrelevant to me, it's about coding style and probably 
should be continued under a different title, but I'm not interested to 
participate in it.


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


Re: for -- else: what was the motivation?

2022-10-10 Thread Chris Angelico
On Mon, 10 Oct 2022 at 20:56, Axy via Python-list
 wrote:
>
> > The else is always coming with the break, not the for.
> However, the compiler does not complain.
> >   There are [for ...], [for...break...], and[for...break...else],
>
> That's implied and contradicts Zen of Python, I think. If "else" came
> with "break" there had to be a strong indication of that, namely
> indentation, as it takes place for all other statements with their
> clauses. However, there's no such an explicit connection between "break"
> and "else". That's the point.
>
> Well, sorry for this addition to the discussion which went weird way. I
> should had to be cautious mentioning particular coding style, that's a
> totally different subject, actually. Let's close it at last.
>
> >   but the [for...else] is insane.
> Not in Python.
>

Not sure what you mean, but a for-else without a break is quite
useless. What exactly ARE you arguing here?

The else is associated with the break to the exact extent that one is
essential to the other's value.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Chris Angelico
On Mon, 10 Oct 2022 at 20:46, Karsten Hilbert  wrote:
>
> Am Sun, Oct 09, 2022 at 09:58:14AM + schrieb Stefan Ram:
>
> >   I often follow this rule. For me, it's about readability. Compare:
> >
> > if not open( disk ):
> > error( "Can't open disk" )
> > else:
> > printf( "now imagine there's some larger block here" )
> ... ad infinitum 
>
> Should this not be
>
> if not open( disk ):
> error( "Can't open disk" )
> else:
> do_lots_of_things_with(disk)
>
> as for readability ?
>
> Or even
>
> if not open( disk ):
> error( "Can't open disk" )
> return what_needs_to_be_returned
>
> do_lots_of_things_with(disk)
>
> The latter version may need some code reorganization, though.

 I definitely prefer the fail-and-bail version (mainly because, as the
number of possible failure modes increases, the code complexity
increases linearly, whereas with if/else style it will increase
quadratically - you have to edit the entire block, and indent it, for
each one). But contrasting the original two? A complete wash. There's
no readability difference between them.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Axy via Python-list

On 09/10/2022 03:33, Jach Feng wrote:

Axy 在 2022年10月8日 星期�
�上午11:39:44 [UTC+8] 的信中寫道:

Hi there,

this is rather a philosophical question, but I assume I miss something.
I don't remember I ever used else clause for years I was with python and
my expectation was it executed only if the the main body was never run.
Ha-ha! I was caught by this mental trap.

So, seriously, why they needed else if the following pieces produce same
result? Does anyone know or remember their motivation?

Just curious.

Axy.

print('--- with else')


for i in [1,2,3]:
 print(i)
else:
 print(4)

for i in []:
 print(i)
else:
 print(5)

print('--- without else')

for i in [1,2,3]:
 print(i)
print(4)

for i in []:
 print(i)
print(5)

The else is always coming with the break, not the for.

However, the compiler does not complain.

  There are [for ...], [for...break...], and[for...break...else],


That's implied and contradicts Zen of Python, I think. If "else" came 
with "break" there had to be a strong indication of that, namely 
indentation, as it takes place for all other statements with their 
clauses. However, there's no such an explicit connection between "break" 
and "else". That's the point.


Well, sorry for this addition to the discussion which went weird way. I 
should had to be cautious mentioning particular coding style, that's a 
totally different subject, actually. Let's close it at last.



  but the [for...else] is insane.

Not in Python.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread Karsten Hilbert
Am Sun, Oct 09, 2022 at 09:58:14AM + schrieb Stefan Ram:

>   I often follow this rule. For me, it's about readability. Compare:
>
> if not open( disk ):
> error( "Can't open disk" )
> else:
> printf( "now imagine there's some larger block here" )
... ad infinitum 

Should this not be

if not open( disk ):
error( "Can't open disk" )
else:
do_lots_of_things_with(disk)

as for readability ?

Or even

if not open( disk ):
error( "Can't open disk" )
return what_needs_to_be_returned

do_lots_of_things_with(disk)

The latter version may need some code reorganization, though.

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Jach Feng
Axy 在 2022年10月8日 星期六上午11:39:44 [UTC+8] 的信中寫道:
> Hi there, 
> 
> this is rather a philosophical question, but I assume I miss something. 
> I don't remember I ever used else clause for years I was with python and 
> my expectation was it executed only if the the main body was never run. 
> Ha-ha! I was caught by this mental trap. 
> 
> So, seriously, why they needed else if the following pieces produce same 
> result? Does anyone know or remember their motivation? 
> 
> Just curious. 
> 
> Axy. 
> 
> print('--- with else') 
> 
> 
> for i in [1,2,3]: 
> print(i) 
> else: 
> print(4) 
> 
> for i in []: 
> print(i) 
> else: 
> print(5) 
> 
> print('--- without else') 
> 
> for i in [1,2,3]: 
> print(i) 
> print(4) 
> 
> for i in []: 
> print(i) 
> print(5)
The else is always coming with the break, not the for. There are [for ...], 
[for...break...], and[for...break...else], but the [for...else] is insane.

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


Re: for -- else: what was the motivation?

2022-10-10 Thread rbowman

On 10/8/22 22:37, Axy wrote:
Python is awesome because it's semantic is clear for the majority, but 
there are places that look odd. In case of "for", "else" looks logically 
tied with "for" clause, but actually it is not. It's tied with "break" 
statement and I overlooked that even after re-reading the language 
reference. If "else" was named like "never_broken_loop" or "nobreak", 
the semantic would be perfectly clear. But, what's done is done.


It is sort of an overload for else. It does save an explicit test. For 
example, in C


for (i-0; ihttps://mail.python.org/mailman/listinfo/python-list


RE: for -- else: what was the motivation?

2022-10-09 Thread avi.e.gross
Chris, a short(er) answer to your addition below.

I did not at first share your perception but maybe do now. If the argument
was that ELSE and other constructs like FINALLY or CATCH are horrible
because they follow other code and important things should be first, that is
a silly argument. Many are at the end precisely because they are not the
main code but have a role to play in making sure various conditions are
dealt with. What some of us ended up discussing was whether the advice made
much sense in a broader context and were reasonable to strive for. Many of
us say not as important as many other things, or not important at all.

I note some people looked at the way C had a FOR loop with three parts
between semicolons up front as syntactic sugar. No doubt clauses like ELSE
could in some way be moved around but the result may well violate other
sensibilities as that did because it is a rather nonstandard syntax.

I have seen languages with CASE or SWITCH statements that fall through and
allow some code to be written once and executed for several scenarios.
Others loathe the idea and want each case self-contained. There is no one
answer everyone likes. Languages are huge experiments for differing ideas.

But it is largely IRRELEVANT in that Python already made the decision and
for now it is what it is. We had a different argument a while back as to how
the word  ELSE captured what is happening linguistically and for many here
IT DOES NOT. But once you KNOW what it does, and you choose to use it, then
it works just as well as any other words because it is what it is. If having
an ELSE late disqualifies Python for this person, use another language! Of
course, PHP may not be ideal for so many other reasons!

 


-Original Message-
From: Python-list  On
Behalf Of Chris Angelico
Sent: Monday, October 10, 2022 12:21 AM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

On Mon, 10 Oct 2022 at 14:59,  wrote:
>
> >>>Which is more disparaging: "I couldn't find anyone suggesting this" 
> >>>or
> "The only place I could find it was a PHP style guide"?
> >>>ChrisA
>
> Chris,
>
> If someone says they heard something from their own personal guru, 
> people often do not feel threatened or argue. I often am told 
> nutrition or medical or other advice that I simply ignore especially 
> if it is about exotic herbs to use or weird ideas like homeopathy or 
> that I should use language X because it is the only way to a haven or
heaven or whatever.
>
> What we had here was someone suggesting their advice was WELL-KNOWN 
> followed by lots of people sputtering about not having heard of it. I 
> actually think the advice would be reasonable in many circumstances as 
> long as it did not conflict with dozens of goals I find more 
> compelling but which vary on a case by case basis such as whether I am 
> prototyping something I will use once, ...

It's clearly not all that well known (none of us have heard of it, and it's
not exactly prominent on the internet), and it seems that most of us
disagree that it's even good advice. So, it's not really a good argument
against for-else.

> I have studied PHP but have never felt a need to use it and arguably 
> the roles it has played are often done commonly by other programs or
methods.

That's because PHP is terrible.

> So in my view, the objection is not about PHP but about uniqueness. If 
> the author of one Python textbook and no others, suggest that your 
> code should declare all imports in alphabetical order then declare all 
> functions in alphabetical order, they can not only safely be ignored, 
> but perhaps not taken seriously as imports sometimes need to be done 
> carefully if something needs something else and if a language needs 
> functions to be defined before another function body calls them, ...

It's not JUST about uniqueness. It's also that nobody but PHP programmers
seem to care about it. That's on par with going to an art supplies forum and
trying to argue that you should lay out your paints in a specific order,
because some kindergarten teacher always does it that way for the kids'
fingerpainting sessions.

No, actually, that's unfair to fingerpainting kindergarteners.

> But some people seem to miss a point we have discussed. The odd 
> clauses like ELSE after a loop (and quite a few variants in similar 
> and different cases) often provide guarantees such as making sure a file
opened is closed.

Citation needed.

> Are these things out of the way? Yes, but so what? I see things as a 
> whole not as just a single screen shot. If a loop has several optional 
> clauses lie we are discussing and you know they are normally near the 
> end, then look for them where they are.

So what's your point?

> I know some languages, JavaScript being an example, may have thing

Re: for -- else: what was the motivation?

2022-10-09 Thread Chris Angelico
On Mon, 10 Oct 2022 at 14:59,  wrote:
>
> >>>Which is more disparaging: "I couldn't find anyone suggesting this" or
> "The only place I could find it was a PHP style guide"?
> >>>ChrisA
>
> Chris,
>
> If someone says they heard something from their own personal guru, people
> often do not feel threatened or argue. I often am told nutrition or medical
> or other advice that I simply ignore especially if it is about exotic herbs
> to use or weird ideas like homeopathy or that I should use language X
> because it is the only way to a haven or heaven or whatever.
>
> What we had here was someone suggesting their advice was WELL-KNOWN followed
> by lots of people sputtering about not having heard of it. I actually think
> the advice would be reasonable in many circumstances as long as it did not
> conflict with dozens of goals I find more compelling but which vary on a
> case by case basis such as whether I am prototyping something I will use
> once, ...

It's clearly not all that well known (none of us have heard of it, and
it's not exactly prominent on the internet), and it seems that most of
us disagree that it's even good advice. So, it's not really a good
argument against for-else.

> I have studied PHP but have never felt a need to use it and arguably the
> roles it has played are often done commonly by other programs or methods.

That's because PHP is terrible.

> So in my view, the objection is not about PHP but about uniqueness. If the
> author of one Python textbook and no others, suggest that your code should
> declare all imports in alphabetical order then declare all functions in
> alphabetical order, they can not only safely be ignored, but perhaps not
> taken seriously as imports sometimes need to be done carefully if something
> needs something else and if a language needs functions to be defined before
> another function body calls them, ...

It's not JUST about uniqueness. It's also that nobody but PHP
programmers seem to care about it. That's on par with going to an art
supplies forum and trying to argue that you should lay out your paints
in a specific order, because some kindergarten teacher always does it
that way for the kids' fingerpainting sessions.

No, actually, that's unfair to fingerpainting kindergarteners.

> But some people seem to miss a point we have discussed. The odd clauses like
> ELSE after a loop (and quite a few variants in similar and different cases)
> often provide guarantees such as making sure a file opened is closed.

Citation needed.

> Are these things out of the way? Yes, but so what? I see things as a whole
> not as just a single screen shot. If a loop has several optional clauses lie
> we are discussing and you know they are normally near the end, then look for
> them where they are.

So what's your point?

> I know some languages, JavaScript being an example, may have things you
> might consider odd such as promoting some things like function definitions
> found further in your code to near the top so you can use a function that is
> not defined till later even without something like a forward declaration
> used in other languages.

I've hardly ever seen good code that actually uses that. And when it
did, it usually wasn't deliberate. Most well-written JS code will do
the same thing that Python code does, calling things that have already
been defined (if not lexically then temporally). No hoisting needed.

> I am now going to stop replying on this topic as I have said way too much
> and am not in particular disagreement if we are discussing preferences and
> ideas. I see TOOLS here, not religion. Use what works or that has to be used
> for a task but don't take any one thing too seriously.

Yes, I see tools too. And this thread started out with a discussion of
the for-else construct, which was disparaged because it violated a
rule that nobody here has heard of, few agree with, and has exceptions
already.

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


RE: for -- else: what was the motivation?

2022-10-09 Thread avi.e.gross
>>>Which is more disparaging: "I couldn't find anyone suggesting this" or
"The only place I could find it was a PHP style guide"?
>>>ChrisA

Chris,

If someone says they heard something from their own personal guru, people
often do not feel threatened or argue. I often am told nutrition or medical
or other advice that I simply ignore especially if it is about exotic herbs
to use or weird ideas like homeopathy or that I should use language X
because it is the only way to a haven or heaven or whatever.

What we had here was someone suggesting their advice was WELL-KNOWN followed
by lots of people sputtering about not having heard of it. I actually think
the advice would be reasonable in many circumstances as long as it did not
conflict with dozens of goals I find more compelling but which vary on a
case by case basis such as whether I am prototyping something I will use
once, ...

I have studied PHP but have never felt a need to use it and arguably the
roles it has played are often done commonly by other programs or methods.
Some people might say the same for many languages that are going extinct or
that have had to change and adapt to keep being relevant. Had the user
mention this was advice given regarding programs in the original BASIC or in
COBOL or PASCAL or lots of other languages I may have once used but rarely
see much point in caring about, it would be no different.

But having ONE source is troublesome. I mean most languages used will
suggest some form of making some kinds of variable names meaningful within
various constraints. The constraints may be that the maximum length is
bounded or that it cannot start with a number (or perhaps underscore) or
contain some characters. But other advice varies enough that there is no
RIGHT or WRONG across languages. I have seen suggestion to use camelCase or
use periods or underscores between parts of a variable name. I have seen
suggestions to use a unique prefix or suffix to mark all your own variables
as a way to minimize the chance of namespace collisions. Some languages
suggest or even enforce that some names be all upper case or have an initial
uppercase letter while others should be completely lower case. I mean things
like function names versus method names versus class names and so on. 

The more global advice is ADVICE that suggests whatever method you choose,
be consistent. If you make class names a certain way, do it as much as
possible for all class names and avoid doing the same thing for non-class
names. I think quite a few suggestions fall into the category that they are
similar or abstractly enough suggested in many programming languages and by
many people. There may be a big enough consensus, perhaps with some
outliers, that it may be accepted as reasonable advice to not be ignored
without good reasons. 

So in my view, the objection is not about PHP but about uniqueness. If the
author of one Python textbook and no others, suggest that your code should
declare all imports in alphabetical order then declare all functions in
alphabetical order, they can not only safely be ignored, but perhaps not
taken seriously as imports sometimes need to be done carefully if something
needs something else and if a language needs functions to be defined before
another function body calls them, ...

I was not questioning that someone had heard this advice somewhere and did
not just make it up. Others searching had trouble finding it but that does
not prove anything. Someone finally found one example, which is fine and I
suspect there may be other examples found if the search was broader. I
suspect there are plenty of places that advise that you should write such
code so the main things is visible on the current screen and not buried
deeply.

But some people seem to miss a point we have discussed. The odd clauses like
ELSE after a loop (and quite a few variants in similar and different cases)
often provide guarantees such as making sure a file opened is closed. If you
look at a Python protocol such as WITH, then things implementing it arrange
it so under most circumstances other than pulling a power line out of the
wall, the darn file gets closed no matter how you exit the area, and other
scenarios try to clean things up even as exceptions are being handled.
Sometimes not using these constructs and using something you think is
identical but looks better to you, can result in unanticipated behavior.
Putting items in a finally or other such clause can be meaningful and
sometimes makes some things quite explicit and reliable. 

Are these things out of the way? Yes, but so what? I see things as a whole
not as just a single screen shot. If a loop has several optional clauses lie
we are discussing and you know they are normally near the end, then look for
them where they are. 

I know some languages, JavaScript being an example, may have things you
might consider odd such as promoting some things like function definitions
found further in your code to near the top so 

RE: for -- else: what was the motivation?

2022-10-09 Thread avi.e.gross
les. This does not sound 
like an improvement over one longer function.

But yet, sometimes not. You might decide a good way to handle this is to use a 
dictionary containing all possible keys as keys and varying small functions as 
arguments. This could make your main function fairly small, once the dictionary 
had been created using many long lines.

So you might say that when evaluating multiple possible solutions, one of 
several guiding mechanisms is to use fairly short functions. But adding may 
guiding principles opens up the door for many conflicts so add one saying that 
if your manager or reviewers insist you do it a specific way, forget the rest 
unless you do not value your job!

Anyone who has read this far, you have my sympathies. LOL! Like me, I suggest 
you (and I) get a life! In life, there often are no unique right answers albeit 
an infinite number of wrong answers.




-Original Message-
From: Python-list  On 
Behalf Of dn
Sent: Sunday, October 9, 2022 7:41 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list  wrote:

> "shortest block first"

Have never heard this advice before. Kind-of rankled with me, as it did for 
others.

Enquiring minds want to know... Played Duck, duck, go on this: zero hits 
amongst a pile of similar phrases - turns-out there's an algorithm with a 
similar name, but not related, and an electronics approach (way too 'low' a 
level for translation to us though).

Tried prefixing with "program" but no such advice to programmers or program[me] 
designers.

Tried prefixing with "python", but equal lack of joy.

Would OP please quote source?


On 10/10/2022 05.56, Peter J. Holzer wrote:
> On 2022-10-09 12:18:09 -0400, Avi Gross wrote:
>> Smallest code blocks first may be a more modern invention.

None of the recent-grads or new-hires I've asked this morning (it's already 
Monday over-here!) have used or heard the term.


>> Some would argue for a rule related to efficiency of execution. When you
>> have multiple blocks as in an if-else or case statement with multiple
>> choices, that you order the most common cases first. Those shorten
>> execution more often than the rarer cases especially the ones that should
>> never happen.
> 
> Those of us who started programming on 8 bit homecomputers of course
> have efficiency always at the back of their heads, but I find this

... for mainframes just as much as micro-computers!

Regarding execution-efficiencies, I'm sure @Avi knows better than I: It 
seems likely that Python, as an interpreted language, will create 
'blocks' of its virtual-machine code in the same order as they appear in 
the Python-source. However, aren't there optimising compilers which do 
something intelligent with the equivalent clauses/suites in other languages?

Regardless, is a Jump-instruction which transfers else-control to a 
block five machine-instructions 'down', any less efficient than a jump 
which spans 50-instructions?


>> So not a rule but realistically not always a bad idea to write code in a
>> way that draws the attention of readers along the main path of execution
>> and perhaps not showing all the checking for odd cases first.
> 
> much more important. Putting the main path first makes it easier to
> understand what the code is supposed to do normally. All those pesky
> exceptions are in the "small print" below.

Absolutely! Has the term "readability" been used 'here'?

Human nature (or is it that of computer programmers in-particular) is to 
be optimistic: it will work [this time*]. Accordingly, a colleague talks 
of always coding 'the happy line' first (meaning line of logic, cf 
source-code).

Contrarily, for while-True (infinite) loops, and particularly recursive 
algorithms, the [wise] counsel is to code the end-condition first. 
(always know your closest exit! "The nearest exit may be behind you"...)


Indeed, dare I say, this optimistic-approach is pythonic. Taking an 
over-simple, two-value division example, the approach is:

try:
 a = b / c
except ZeroDivisionError:
 ... clean-up the mess ...

which contrasts the EAFP philosophy of Python versus the LBYL 
expectation of (many) other languages:

assert c != 0
a = b / c

That said, as "Data Science" use of Python expands, it is bringing more 
and more needs for an LBYL attitude, eg "data cleaning".

(EAFP, LBYL? https://docs.python.org/3.9/glossary.html)


> There is of course the opposite view that you should just get all of the
> confounding factors out of the way first, so that the default is also
> the common case. I also do that sometimes, but then I don't hide this in
> in an else: clause but do something like this:
> 
> for item in whatever:
>  if not_this_one(item):
>  continue
>  if neit

RE: for -- else: what was the motivation?

2022-10-09 Thread avi.e.gross
f pipeline are even close to
being the same.


-Original Message-
From: Python-list  On
Behalf Of Peter J. Holzer
Sent: Sunday, October 9, 2022 4:02 PM
To: python-list@python.org
Subject: Re: for -- else: what was the motivation?

On 2022-10-09 15:32:13 -0400, Avi Gross wrote:
> and of course no pipelines.

Since you've now used that term repeatedly: What is a pipeline in Python?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"

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


Re: for -- else: what was the motivation?

2022-10-09 Thread Chris Angelico
On Mon, 10 Oct 2022 at 11:52, MRAB  wrote:
>
> On 2022-10-10 00:40, dn wrote:
> > On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
> >  wrote:
> >
> >> "shortest block first"
> >
> > Have never heard this advice before. Kind-of rankled with me, as it did
> > for others.
> >
> > Enquiring minds want to know... Played Duck, duck, go on this: zero hits
> > amongst a pile of similar phrases - turns-out there's an algorithm with
> > a similar name, but not related, and an electronics approach (way too
> > 'low' a level for translation to us though).
> >
> > Tried prefixing with "program" but no such advice to programmers or
> > program[me] designers.
> >
> > Tried prefixing with "python", but equal lack of joy.
> >
> > Would OP please quote source?
> >
> [snip]
> After a few minutes searching I found this:
>
> https://docs.typo3.org/m/typo3/reference-coreapi/9.5/en-us/CodingGuidelines/CglPhp/PhpFileFormatting/PhpSyntaxFormatting.html
>
> """It is recommended to create conditions so that the shortest block of
> code goes first."""

Which is more disparaging: "I couldn't find anyone suggesting this" or
"The only place I could find it was a PHP style guide"?

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


Re: for -- else: what was the motivation?

2022-10-09 Thread dn




On 10/10/2022 13.47, MRAB wrote:

On 2022-10-10 00:40, dn wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
 wrote:


"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did
for others.

Enquiring minds want to know... Played Duck, duck, go on this: zero hits
amongst a pile of similar phrases - turns-out there's an algorithm with
a similar name, but not related, and an electronics approach (way too
'low' a level for translation to us though).

Tried prefixing with "program" but no such advice to programmers or
program[me] designers.

Tried prefixing with "python", but equal lack of joy.

Would OP please quote source?


[snip]
After a few minutes searching I found this:

https://docs.typo3.org/m/typo3/reference-coreapi/9.5/en-us/CodingGuidelines/CglPhp/PhpFileFormatting/PhpSyntaxFormatting.html

"""It is recommended to create conditions so that the shortest block of 
code goes first."""


Thanks for this!

So, a Domain-Specific Language for a CMS.

If this is only reference, then hardly a tenet of ComSc thinking or 
programming-languages!



For fun: Typo3 is based on PHP. Advice (apparently) not replicated in 
PHP-docs (if, else, etc).

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread MRAB

On 2022-10-10 00:40, dn wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
 wrote:


"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did
for others.

Enquiring minds want to know... Played Duck, duck, go on this: zero hits
amongst a pile of similar phrases - turns-out there's an algorithm with
a similar name, but not related, and an electronics approach (way too
'low' a level for translation to us though).

Tried prefixing with "program" but no such advice to programmers or
program[me] designers.

Tried prefixing with "python", but equal lack of joy.

Would OP please quote source?


[snip]
After a few minutes searching I found this:

https://docs.typo3.org/m/typo3/reference-coreapi/9.5/en-us/CodingGuidelines/CglPhp/PhpFileFormatting/PhpSyntaxFormatting.html

"""It is recommended to create conditions so that the shortest block of 
code goes first."""

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


Re: for -- else: what was the motivation?

2022-10-09 Thread dn
On Sun, 9 Oct 2022 at 15:39, Axy via Python-list 
 wrote:



"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did 
for others.


Enquiring minds want to know... Played Duck, duck, go on this: zero hits 
amongst a pile of similar phrases - turns-out there's an algorithm with 
a similar name, but not related, and an electronics approach (way too 
'low' a level for translation to us though).


Tried prefixing with "program" but no such advice to programmers or 
program[me] designers.


Tried prefixing with "python", but equal lack of joy.

Would OP please quote source?


On 10/10/2022 05.56, Peter J. Holzer wrote:

On 2022-10-09 12:18:09 -0400, Avi Gross wrote:

Smallest code blocks first may be a more modern invention.


None of the recent-grads or new-hires I've asked this morning (it's 
already Monday over-here!) have used or heard the term.




Some would argue for a rule related to efficiency of execution. When you
have multiple blocks as in an if-else or case statement with multiple
choices, that you order the most common cases first. Those shorten
execution more often than the rarer cases especially the ones that should
never happen.


Those of us who started programming on 8 bit homecomputers of course
have efficiency always at the back of their heads, but I find this


... for mainframes just as much as micro-computers!

Regarding execution-efficiencies, I'm sure @Avi knows better than I: It 
seems likely that Python, as an interpreted language, will create 
'blocks' of its virtual-machine code in the same order as they appear in 
the Python-source. However, aren't there optimising compilers which do 
something intelligent with the equivalent clauses/suites in other languages?


Regardless, is a Jump-instruction which transfers else-control to a 
block five machine-instructions 'down', any less efficient than a jump 
which spans 50-instructions?




So not a rule but realistically not always a bad idea to write code in a
way that draws the attention of readers along the main path of execution
and perhaps not showing all the checking for odd cases first.


much more important. Putting the main path first makes it easier to
understand what the code is supposed to do normally. All those pesky
exceptions are in the "small print" below.


Absolutely! Has the term "readability" been used 'here'?

Human nature (or is it that of computer programmers in-particular) is to 
be optimistic: it will work [this time*]. Accordingly, a colleague talks 
of always coding 'the happy line' first (meaning line of logic, cf 
source-code).


Contrarily, for while-True (infinite) loops, and particularly recursive 
algorithms, the [wise] counsel is to code the end-condition first. 
(always know your closest exit! "The nearest exit may be behind you"...)



Indeed, dare I say, this optimistic-approach is pythonic. Taking an 
over-simple, two-value division example, the approach is:


try:
a = b / c
except ZeroDivisionError:
... clean-up the mess ...

which contrasts the EAFP philosophy of Python versus the LBYL 
expectation of (many) other languages:


assert c != 0
a = b / c

That said, as "Data Science" use of Python expands, it is bringing more 
and more needs for an LBYL attitude, eg "data cleaning".


(EAFP, LBYL? https://docs.python.org/3.9/glossary.html)



There is of course the opposite view that you should just get all of the
confounding factors out of the way first, so that the default is also
the common case. I also do that sometimes, but then I don't hide this in
in an else: clause but do something like this:

for item in whatever:
 if not_this_one(item):
 continue
 if neither_this_one(item):
 continue
 if cant_continue(item):
 break
 if oopsie():
 raise SomeError()

 do_something_with(item)
 and_some_more(item)
 we_are_done(item)

which shows visually what the main purpose of the loop (or function or
other block) is.


Nicely stated!

NB I've seen sufficient of @Peter's posts to know that this was never 
(even implied to be) intended as a snippet for all occasions!



It also illustrates why such is less readable: because we have to scan 
four if-statements before we can 'see' the purpose of the loop. My 
'itch' would be to extract this code 'out' to a function - that way the 
name will convey the somewhat-obscured purpose of the loop.



Alternately, reduce the 'distractions':-

try:
for item in whatever:
inspect_the_data( item )
do_something_with(item)
and_some_more(item)
we_are_done(item)
except SomeError:
...
except CustomBreakException:
... ?pass?  # same effect as break

by 'hiding' in:

def inspect_the_data( item ):
if not_this_one(item):
continue
if neither_this_one(item):
continue
if cant_continue(item):
raise CustomBreakException  # was break
if oopsie():
raise SomeError()



Re: for -- else: what was the motivation?

2022-10-09 Thread Peter J. Holzer
On 2022-10-09 15:32:13 -0400, Avi Gross wrote:
> and of course no pipelines.

Since you've now used that term repeatedly: What is a pipeline in
Python?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Avi Gross
Peter,

There can be excellent reasons to undo a pipeline like I described. I often
write it carefully in smaller chunks while debugging and make it more
elegant later ...

But someone amused me by explaining they were going to let people believe
the code was written by them so it had to fit their style and abilities.
That meant removing most of my comments, renaming some variables, taking
out code that checked things like whether a file existed before opening it
and of course no pipelines. It had to be downgraded and had I known, I
could have easily given them code written as if it was in some poorer
language.

Python has idioms often used in making pipes of a sort but in languages
with other forms, such as R, debugging is not that difficult as you can
insert functions in middle of a pipeline that print what you want but
return the data structure they were fed for the next step in the pipeline.
When done, remove the lines with such entries or change the function
definition or something like that.

Objects used as pipelines do not do this as easily as you may need to add
methods ...


On Sun, Oct 9, 2022, 1:17 PM Peter J. Holzer  wrote:

> On 2022-10-09 12:34:22 -0400, Avi Gross wrote:
> > I have seen programmers who have taken an elegant pipeline I have built
> > apart and made it into many lines of code reassignment the value of each
> > step to the same or different variables and other ways of lengthening or
> > obscuring my intent.
>
> I have certainly done that (not with your code, AFAIK). The problem with
> those beautiful one-liners is that they are really hard to debug. So if
> I can't convince myself that they are correct just by reading them I
> have to split them over multiple lines so I can add breakpoints or log
> messages. Of course I could put it together again afterwards, but I
> would argue that if I didn't understand it the first time it's probably
> better to leave it in its more verbose and debuggable state.
>
> Of course I have also done the opposite: Taken some messy and
> complicated code and simplified it into a simple generator expression.
> In fact I would say that I code tends to be shorter after I fixed a bug
> than before.
>
>
> > So although size may matter, so can sighs.
>
> :-)
>
> hp
>
> --
>_  | Peter J. Holzer| Story must make more sense than reality.
> |_|_) ||
> | |   | h...@hjp.at |-- Charles Stross, "Creative writing
> __/   | http://www.hjp.at/ |   challenge!"
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Avi Gross
Fair enough, Chris. There may be some overlap with the size of code for the
most common cases but sometimes the opposite as those may be more complex
to deal with.

A reality for many programmers today is to not micromanage too early as
things are often fast enough and any tweaking is best done only in critical
areas. The emphasis may be on the programmer experience in writing fast
code with fewer errors. Perhaps secondary but often important is making the
code maintainable and in my experience that can often be best done by
choosing meaningful names and brief selective comments than by worrying
about the size of blocks of code.

But others obviously preach what they think works for them even when it may
constrain others more than it helps.

I have seen people suggest that all variables have short names like a3 but
that does not mean it improves anything other than the size of the code and
parsing it. The loss in readability and so on probably is worse.


On Sun, Oct 9, 2022, 12:53 PM Chris Angelico  wrote:

> On Mon, 10 Oct 2022 at 03:46, Avi Gross  wrote:
> >
> > Chris, I was not arguing that at all.
>
> Maybe not intentionally, but you did lend a lot of weight to that argument
> :)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Peter J. Holzer
On 2022-10-09 12:34:22 -0400, Avi Gross wrote:
> I have seen programmers who have taken an elegant pipeline I have built
> apart and made it into many lines of code reassignment the value of each
> step to the same or different variables and other ways of lengthening or
> obscuring my intent.

I have certainly done that (not with your code, AFAIK). The problem with
those beautiful one-liners is that they are really hard to debug. So if
I can't convince myself that they are correct just by reading them I
have to split them over multiple lines so I can add breakpoints or log
messages. Of course I could put it together again afterwards, but I
would argue that if I didn't understand it the first time it's probably
better to leave it in its more verbose and debuggable state.

Of course I have also done the opposite: Taken some messy and
complicated code and simplified it into a simple generator expression.
In fact I would say that I code tends to be shorter after I fixed a bug
than before.


> So although size may matter, so can sighs.

:-)

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Peter J. Holzer
On 2022-10-09 12:18:09 -0400, Avi Gross wrote:
> Smallest code blocks first may be a more modern invention.
> 
> Some would argue for a rule related to efficiency of execution. When you
> have multiple blocks as in an if-else or case statement with multiple
> choices, that you order the most common cases first. Those shorten
> execution more often than the rarer cases especially the ones that should
> never happen.

Those of us who started programming on 8 bit homecomputers of course
have efficiency always at the back of their heads, but I find this

> So not a rule but realistically not always a bad idea to write code in a
> way that draws the attention of readers along the main path of execution
> and perhaps not showing all the checking for odd cases first.

much more important. Putting the main path first makes it easier to
understand what the code is supposed to do normally. All those pesky
exceptions are in the "small print" below.

There is of course the opposite view that you should just get all of the
confounding factors out of the way first, so that the default is also
the common case. I also do that sometimes, but then I don't hide this in
in an else: clause but do something like this:

for item in whatever:
if not_this_one(item):
continue
if neither_this_one(item):
continue
if cant_continue(item):
break
if oopsie():
raise SomeError()

do_something_with(item)
and_some_more(item)
we_are_done(item)

which shows visually what the main purpose of the loop (or function or
other block) is.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Axy via Python-list




Since many languages allow placing multiple statements on one line or
spreading one over many lines, it seems that the number of lines in code
can be adjusted.

If I have a line like:

  Alpha, beta, gamma, delta = 1, 2, 3, 4

Could that be rewritten as 4 or more lines?


Surely! Especially if you're paid for SLOC :-)))

By the way, does "else" clause after affect cyclomatic complexity 
metric? I mean "for" loops.


Axy.

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


Re: for -- else: what was the motivation?

2022-10-09 Thread Chris Angelico
On Mon, 10 Oct 2022 at 03:46, Avi Gross  wrote:
>
> Chris, I was not arguing that at all.

Maybe not intentionally, but you did lend a lot of weight to that argument :)

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


Re: for -- else: what was the motivation?

2022-10-09 Thread Avi Gross
Chris, I was not arguing that at all.

I was saying some rationales about how to order  choices exist based on
ideas like efficiency or other considerations.  Sometimes people are
mistaken as something may take constant time as implemented. And yes, many
rules have countless exceptions. For example, if something is expected to
rarely or never happen, code within that branch may not be needed to be
optimized in any way as long as it works in the remote chance it is called.

I think what was suggested here is more about code readability
considerations and for some of us, making us stand on our heads to puzzle
things out is harder than ordering longer items ...

On Sun, Oct 9, 2022, 12:30 PM Chris Angelico  wrote:

> On Mon, 10 Oct 2022 at 03:22, Avi Gross  wrote:
> >
> > Smallest code blocks first may be a more modern invention.
> >
> > Some would argue for a rule related to efficiency of execution. When you
> > have multiple blocks as in an if-else or case statement with multiple
> > choices, that you order the most common cases first. Those shorten
> > execution more often than the rarer cases especially the ones that should
> > never happen.
> >
>
> Seems fairly dubious and full of special-cases. If you want to follow
> that rule, it should be easy enough to still permit for-else clauses.
> It's an extremely weak argument against for-else.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Avi Gross
Since many languages allow placing multiple statements on one line or
spreading one over many lines, it seems that the number of lines in code
can be adjusted.

If I have a line like:

 Alpha, beta, gamma, delta = 1, 2, 3, 4

Could that be rewritten as 4 or more lines?

I have seen programmers who have taken an elegant pipeline I have built
apart and made it into many lines of code reassignment the value of each
step to the same or different variables and other ways of lengthening or
obscuring my intent.

So although size may matter, so can sighs.

On Sun, Oct 9, 2022, 4:24 AM Peter J. Holzer  wrote:

> On 2022-10-09 05:37:59 +0100, Axy via Python-list wrote:
> > Actually the reason I never used "else" was the violation of the rule
> > of beauty "shortest block first".
>
> That's a weird rule.
>
> I can see justifications for "most common case first" and "most special
> case first", but ordering the cases in an if/elif/else statement by
> length seems like ordering books by color: It may be pretty, but it
> doesn't make them easy to find.
>
> hp
>
> --
>_  | Peter J. Holzer| Story must make more sense than reality.
> |_|_) ||
> | |   | h...@hjp.at |-- Charles Stross, "Creative writing
> __/   | http://www.hjp.at/ |   challenge!"
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Chris Angelico
On Mon, 10 Oct 2022 at 03:22, Avi Gross  wrote:
>
> Smallest code blocks first may be a more modern invention.
>
> Some would argue for a rule related to efficiency of execution. When you
> have multiple blocks as in an if-else or case statement with multiple
> choices, that you order the most common cases first. Those shorten
> execution more often than the rarer cases especially the ones that should
> never happen.
>

Seems fairly dubious and full of special-cases. If you want to follow
that rule, it should be easy enough to still permit for-else clauses.
It's an extremely weak argument against for-else.

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


Re: for -- else: what was the motivation?

2022-10-09 Thread Karsten Hilbert
Am Sun, Oct 09, 2022 at 05:37:59AM +0100 schrieb Axy via Python-list:

> Python is awesome because it's semantic is clear for the majority, but there 
> are places
> that look odd. In case of "for", "else" looks logically tied with "for" 
> clause, but
> actually it is not. It's tied with "break" statement and I overlooked that 
> even after
> re-reading the language reference. If "else" was named like 
> "never_broken_loop" or
> "nobreak", the semantic would be perfectly clear. But, what's done is done.

Or, "eventually". Sadly, "finally" is already taken, and with
slightly different semantics...

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Avi Gross
Smallest code blocks first may be a more modern invention.

Some would argue for a rule related to efficiency of execution. When you
have multiple blocks as in an if-else or case statement with multiple
choices, that you order the most common cases first. Those shorten
execution more often than the rarer cases especially the ones that should
never happen.

There are obvious exceptions like the default having to be last, albeit
some languages allow the default to be inserted anywhere visually even if
the code sort of runs last.

But negating a condition so smaller code appears first may have some cost.
I mean if !function() may be slower as the negating is an extra step. But
it may be even slower if the inversion is done using a wrapper function
that simply inverts the return value from the other function.

I think sometimes a comment placed carefully that explains the code and
logic in concise form is a simpler approach that can be followed by a big
chunk then little chunk without loss of readability.

In the original example the else part can be mentioned before the loop as a
sort of reminder.

In my experience, the size of code often varies within a project so a
smaller chunk may grow as requirements change, such as adding debug or
logging, and large chunks can shrink as common parts of the code get
extracted into functions.

So not a rule but realistically not always a bad idea to write code in a
way that draws the attention of readers along the main path of execution
and perhaps not showing all the checking for odd cases first. I mean as an
example if the argument is of type text then do stuff, else if a number
else if a symbol else if empty  ...

On Sun, Oct 9, 2022, 1:18 AM Chris Angelico  wrote:

> On Sun, 9 Oct 2022 at 16:05, Axy via Python-list 
> wrote:
> >
> >
> > On 09/10/2022 05:47, Chris Angelico wrote:
> > > On Sun, 9 Oct 2022 at 15:39, Axy via Python-list <
> python-list@python.org> wrote:
> > >> Got it, thanks!
> > >>
> > >> Actually the reason I never used "else" was the violation of the rule
> of
> > >> beauty "shortest block first". With if--else you can easily follow
> this
> > >> rule by inverting "if" expression, but with for--else you can't. The
> > >> loop body of the simplest example is already three lines, in real life
> > >> things are much worse.
> > >>
> > > That's not a rule I've ever been taught; how important is it?
> > >
> > > ChrisA
> >
> > It gets important if the lifetime of your project is more than three
> > months and is extremely important if more than 10 years. But, it depends.
>
> Yes, I'm aware that code readability becomes irrelevant for
> short-duration projects. Beside the point. I'm wondering how important
> it really is to have the shortest block first.
>
> > I also might be wrong in terminology, anyway, there are many rules that
> > make programmer's life easier, described in the literature from the old
> > good "How to write unmaintainable code" to "The Art of Readable Code".
> > And I hope there are a lot of recent books on this subject I did not
> > track and read yet.
>
> Also not really a justification for "shortest block first". Wanting
> some elaboration on that. What's the value in it?
>
> Given that for-else is an excellent, if rarely-used, construct, I
> would say that, *at least*, it is worth setting aside this rule for
> that particular situation. It is also generally worth using fewer
> commas than I just did. Take my advice with a grain of salt.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Michael Speer
>Well, the value is productivity. No need to save puzzles "what this
>hanging else belongs to?"

if you get to the point where it's hard to tell which else lines up with
which if or for statement, I would suggest breaking things out into
well-named helper functions rather than worrying over ordering by block size


On Sun, Oct 9, 2022 at 2:26 AM Axy via Python-list 
wrote:

>
> > Yes, I'm aware that code readability becomes irrelevant for
> > short-duration projects. Beside the point. I'm wondering how important
> > it really is to have the shortest block first.
> >
> >> I also might be wrong in terminology, anyway, there are many rules that
> >> make programmer's life easier, described in the literature from the old
> >> good "How to write unmaintainable code" to "The Art of Readable Code".
> >> And I hope there are a lot of recent books on this subject I did not
> >> track and read yet.
> > Also not really a justification for "shortest block first". Wanting
> > some elaboration on that. What's the value in it?
>
> Well, the value is productivity. No need to save puzzles "what this
> hanging else belongs to?" regardless of semantic, which ideally should
> not be a puzzle as well. Code small things first and return early, same
> as taking a test: do easy and quick things first and boring and
> difficult ones later.
>
> Axy.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Peter J. Holzer
On 2022-10-09 05:37:59 +0100, Axy via Python-list wrote:
> Actually the reason I never used "else" was the violation of the rule
> of beauty "shortest block first".

That's a weird rule.

I can see justifications for "most common case first" and "most special
case first", but ordering the cases in an if/elif/else statement by
length seems like ordering books by color: It may be pretty, but it
doesn't make them easy to find.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread Axy via Python-list




Yes, I'm aware that code readability becomes irrelevant for
short-duration projects. Beside the point. I'm wondering how important
it really is to have the shortest block first.


I also might be wrong in terminology, anyway, there are many rules that
make programmer's life easier, described in the literature from the old
good "How to write unmaintainable code" to "The Art of Readable Code".
And I hope there are a lot of recent books on this subject I did not
track and read yet.

Also not really a justification for "shortest block first". Wanting
some elaboration on that. What's the value in it?


Well, the value is productivity. No need to save puzzles "what this 
hanging else belongs to?" regardless of semantic, which ideally should 
not be a puzzle as well. Code small things first and return early, same 
as taking a test: do easy and quick things first and boring and 
difficult ones later.


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


Re: for -- else: what was the motivation?

2022-10-08 Thread Chris Angelico
On Sun, 9 Oct 2022 at 16:05, Axy via Python-list  wrote:
>
>
> On 09/10/2022 05:47, Chris Angelico wrote:
> > On Sun, 9 Oct 2022 at 15:39, Axy via Python-list  
> > wrote:
> >> Got it, thanks!
> >>
> >> Actually the reason I never used "else" was the violation of the rule of
> >> beauty "shortest block first". With if--else you can easily follow this
> >> rule by inverting "if" expression, but with for--else you can't. The
> >> loop body of the simplest example is already three lines, in real life
> >> things are much worse.
> >>
> > That's not a rule I've ever been taught; how important is it?
> >
> > ChrisA
>
> It gets important if the lifetime of your project is more than three
> months and is extremely important if more than 10 years. But, it depends.

Yes, I'm aware that code readability becomes irrelevant for
short-duration projects. Beside the point. I'm wondering how important
it really is to have the shortest block first.

> I also might be wrong in terminology, anyway, there are many rules that
> make programmer's life easier, described in the literature from the old
> good "How to write unmaintainable code" to "The Art of Readable Code".
> And I hope there are a lot of recent books on this subject I did not
> track and read yet.

Also not really a justification for "shortest block first". Wanting
some elaboration on that. What's the value in it?

Given that for-else is an excellent, if rarely-used, construct, I
would say that, *at least*, it is worth setting aside this rule for
that particular situation. It is also generally worth using fewer
commas than I just did. Take my advice with a grain of salt.

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


Re: for -- else: what was the motivation?

2022-10-08 Thread Axy via Python-list



On 09/10/2022 05:47, Chris Angelico wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list  wrote:

Got it, thanks!

Actually the reason I never used "else" was the violation of the rule of
beauty "shortest block first". With if--else you can easily follow this
rule by inverting "if" expression, but with for--else you can't. The
loop body of the simplest example is already three lines, in real life
things are much worse.


That's not a rule I've ever been taught; how important is it?

ChrisA


It gets important if the lifetime of your project is more than three 
months and is extremely important if more than 10 years. But, it depends.


I also might be wrong in terminology, anyway, there are many rules that 
make programmer's life easier, described in the literature from the old 
good "How to write unmaintainable code" to "The Art of Readable Code". 
And I hope there are a lot of recent books on this subject I did not 
track and read yet.


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


Re: for -- else: what was the motivation?

2022-10-08 Thread Chris Angelico
On Sun, 9 Oct 2022 at 15:39, Axy via Python-list  wrote:
>
> Got it, thanks!
>
> Actually the reason I never used "else" was the violation of the rule of
> beauty "shortest block first". With if--else you can easily follow this
> rule by inverting "if" expression, but with for--else you can't. The
> loop body of the simplest example is already three lines, in real life
> things are much worse.
>

That's not a rule I've ever been taught; how important is it?

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


Re: for -- else: what was the motivation?

2022-10-08 Thread Axy via Python-list

Got it, thanks!

Actually the reason I never used "else" was the violation of the rule of 
beauty "shortest block first". With if--else you can easily follow this 
rule by inverting "if" expression, but with for--else you can't. The 
loop body of the simplest example is already three lines, in real life 
things are much worse.


So it was probably the first time I used "else" because I had only one 
line in my loop which appended data packets to the buffer and if "else" 
behaved as I thought it would meant I have no more data and could just 
return early, terminating outer loop with no other boolean logic.


I have no idea why I thought so, some language might had such a 
semantic. Maybe my own I developed 20 years ago, but I could not invent 
that by myself, I definitely had some source of inspiration.


Python is awesome because it's semantic is clear for the majority, but 
there are places that look odd. In case of "for", "else" looks logically 
tied with "for" clause, but actually it is not. It's tied with "break" 
statement and I overlooked that even after re-reading the language 
reference. If "else" was named like "never_broken_loop" or "nobreak", 
the semantic would be perfectly clear. But, what's done is done.


I guess the real motivation was avoiding moving such patterns to a 
separate functions, say, "find_banana" where early returns make "else" 
absolutely unnecessary.


Cheers.

Axy.


On 08/10/2022 06:49, rbowman wrote:

On 10/7/22 21:32, Axy wrote:
So, seriously, why they needed else if the following pieces produce 
same result? Does anyone know or remember their motivation?


In real scenarios there would be more logic in the for block that 
would meet a condition and break out of the loop. If the condition is 
never met, the else block runs. To steal from w3schools:



fruits = ["apple", "peach", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break
else:
  print("Yes we got no bananas")



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


Re: for -- else: what was the motivation?

2022-10-08 Thread rbowman

On 10/7/22 21:32, Axy wrote:
So, seriously, why they needed else if the following pieces produce same 
result? Does anyone know or remember their motivation?


In real scenarios there would be more logic in the for block that would 
meet a condition and break out of the loop. If the condition is never 
met, the else block runs. To steal from w3schools:



fruits = ["apple", "peach", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
break
else:
  print("Yes we got no bananas")


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


Re: for -- else: what was the motivation?

2022-10-07 Thread Dan Stromberg
The else is executed if you don't "break" out of the loop early.

It cuts down on boolean flags.

On Fri, Oct 7, 2022 at 8:40 PM Axy via Python-list 
wrote:

> Hi there,
>
> this is rather a philosophical question, but I assume I miss something.
> I don't remember I ever used else clause for years I was with python and
> my expectation was it executed only if the the main body was never run.
> Ha-ha! I was caught by this mental trap.
>
> So, seriously, why they needed else if the following pieces produce same
> result? Does anyone know or remember their motivation?
>
> Just curious.
>
> Axy.
>
> print('--- with else')
>
>
> for i in [1,2,3]:
>  print(i)
> else:
>  print(4)
>
> for i in []:
>  print(i)
> else:
>  print(5)
>
> print('--- without else')
>
> for i in [1,2,3]:
>  print(i)
> print(4)
>
> for i in []:
>  print(i)
> print(5)
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


for -- else: what was the motivation?

2022-10-07 Thread Axy via Python-list

Hi there,

this is rather a philosophical question, but I assume I miss something. 
I don't remember I ever used else clause for years I was with python and 
my expectation was it executed only if the the main body was never run. 
Ha-ha! I was caught by this mental trap.


So, seriously, why they needed else if the following pieces produce same 
result? Does anyone know or remember their motivation?


Just curious.

Axy.

print('--- with else')


for i in [1,2,3]:
    print(i)
else:
    print(4)

for i in []:
    print(i)
else:
    print(5)

print('--- without else')

for i in [1,2,3]:
    print(i)
print(4)

for i in []:
    print(i)
print(5)
--
https://mail.python.org/mailman/listinfo/python-list


  1   2   >