On Tue, Mar 1, 2022 at 2:23 PM Steven D'Aprano <st...@pearwood.info> wrote:

>     try:
>         do_this()
>         if condition: raise MyBreak
>         do_that()
>         if condition: raise MyBreak
>         do_next_step()
>         if condition: raise MyBreak
>         do_last_step()
>     except MyBreak:
>         pass
>

Why not:

    while True:
        [loop body with ordinary breaks]
        break

It's less to write and almost free of charge*, and it also supports redo
(continue).

MyBreak has the advantage that you can raise it in nested loops and
subfunctions, although that could be a disadvantage since it makes the
control flow confusing.

This goes for repeat-until also: I always write it while True: ... if cond:
break. I just grepped through some personal Python projects and about 40%
of my while-loop conditions are True.

* The break at the end is free, but Python 3.10.2 inserts a NOP at the
location of the while True, and the peephole optimizers of earlier Python
versions have done other things. It looks like there's been a lot of work
on bytecode efficiency in 3.11, so maybe it will become truly free, but I
haven't checked.

3.11 has range-based exception handling (issue 40222), so the try: approach
is free if you don't raise MyBreak (but expensive if you do).
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EBNBHLKGNPGF73QKASXM4JF535AMA2UU/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to