--------------------------------------------------------------------------
EDIT 2024-11-24 Sunday
Chenged the proposal from if break:
(a novel juxtaposition of two keywords) to if_break:
(a single new soft keyword). The former did some damage by giving if
and break
meanings in this context they have nowhere else. The latter is explicit about that they’re intended to be read as a single unit in this context.
Downsides include that I have no experience implementing soft keywords, so can’t really help whoever (if anyone) finds this interesting enough to implement, and that it will take time for syntax colorers (or more generally code-aware tools) to recognize the new soft keyword.
--------------------------------------------------------------------------
Search loops in Python are often written like so:
for ...: # or while
if condition found:
# do _everything_ needed if it's found
break
else:
# do everything needed if it's not found
The proposal is to add a new, optional clause, to handle the “if it’s found” case in a clearer way:
for ...: # or while
if condition found:
break
if_break:
# do everything needed if it's found
else:
# do everything needed if it's not found
if_break
is a new soft keyword, acting as a keyword only as part of loop syntax. Elsewhere it would just be (as it is now) an identifier.
Then:
- The search loop body is solely devoted to searching - better separation of concerns.
- The “found” and “not found” suites are at the same indentation level. Sometimes the “it’s found” condition is discovered in several layers of nested testing, pushing the important part “far off to the right”.
- It’s possible that some cases of breaking from multiple loop levels would be easier, although I expect that “many levels” of this would still be better (more readably) done via the “put the whole thing in a
try
block and raise a custom exception to break out of deep nesting” approach.
for ...:
while ...:
if condition:
break # breaks out of "while"
if_break:
break # if & only if "break" in "while" was executed
- Mnemonic value for those who have a hard time remembering whether
else:
is entered if a break occurred, or didn’t occur.
if_break:
and else:
are both optional. Nothing about the semantics of current code would change, and if_break:
is currently a syntax error. Over time, I’d migrate much of my own code to use if_break:
, but in very simple cases wouldn’t change any of my code. That’s me. YMMV.
Not a big deal, just a “nice to have”. I don’t intend to implement it, but suggest it would be a relatively easy addition for an aspiring core dev to tackle.