replacing `else` with `then` in `for` and `try`

Chris Angelico rosuav at gmail.com
Sat Nov 4 08:39:15 EDT 2017


On Sat, Nov 4, 2017 at 11:22 PM, Jon Ribbens <jon+usenet at unequivocal.eu> wrote:
> On 2017-11-04, Michael Torrie <torriem at gmail.com> wrote:
>> On 11/03/2017 09:06 PM, Chris Angelico wrote:
>>> On Sat, Nov 4, 2017 at 1:57 PM, Michael Torrie <torriem at gmail.com> wrote:
>>>> On 11/03/2017 07:09 PM, Steve D'Aprano wrote:
>>>>> That's incorrect. There are multiple ways to exit a loop that
>>>>> will prevent the `else` block from executing, `break` is only one.
>>>>
>>>> Such as?
>>>
>>> There are many. But other than break, I don't know of any that WOULD
>>> execute the next line of code immediately _after_ the loop.
>>
>> Can you be more specific? What are some of these "many" ways of aborting
>> a loop?  Help a guy out here.
>>
>> I know, for example, that we have exceptions. But those hardly matter in
>> this discussion because they wouldn't execute the else clause either.
>> They'd either be caught elsewhere, or end the program.  sys.exit() can
>> also terminate a for loop, but it terminates the whole program without
>> running the else statement.
>
> Yes, those are the sort of thing that Steve was referring to.
> He was being unhelpfully pedantic. A giant meteor destroying
> the computer the program was running on would prevent the 'else'
> block from executing too.

My definition of "preventing else from executing" is that it would (a)
not execute code inside the else block, and (b) execute unindented
code immediately *after* that else block. Consider a try/finally
block:

try:
    print("Setup")
    ...
finally:
    print("Cleanup")
print("Carrying on")

Before we reach "carrying on", we are guaranteed to pass through
"cleanup". Steve's pedantry is 100% accurate for situations where the
setup and cleanup involve the network; you can't actually guarantee
that the cleanup will be performed (a hard exit will abort the whole
process, a 'kill -9' will shut you down, powering down the computer
means nothing happens), so you have to assume that the cleanup might
not happen (eg with PostgreSQL, the database server will roll back
your transaction and clean up the trash). But AFAIK there is no way to
reach "carrying on" without first executing "cleanup".

With the for-else clause, we have the same valid pedantry, but with a
few differences. A 'return' inside the loop will skip the 'else'
clause (but wouldn't skip a 'finally'), as will any exception. But
neither of those would hit "carrying on" either. AFAIK the only way to
skip the else *and hit the "carrying on" call* is to use 'break'.
That's a non-pedantic interpretation of "skip the else clause".

ChrisA



More information about the Python-list mailing list