for -- else: what was the motivation?

Peter J. Holzer hjp-python at hjp.at
Sun Oct 9 12:56:29 EDT 2022


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.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20221009/518a9e13/attachment.sig>


More information about the Python-list mailing list