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

Ben Bacarisse ben.usenet at bsb.me.uk
Wed Nov 1 21:50:28 EDT 2017


Steve D'Aprano <steve+python at pearwood.info> writes:

> On Thu, 2 Nov 2017 08:12 am, Alexey Muranov wrote:
>
>> what do you think about the idea of replacing "`else`" with "`then`" in
>> the contexts of `for` and `try`?
>
> Yes, this, exactly!!!
>
> (For while and for loops, but not try -- see below.)
>
> I have argued this for many years. The current choice of "else" is painfully
> misleading, and it causes people (including myself) to wrongly guess that
> the "else" block runs only if the for/while block doesn't run at all:
>
>
> # This is wrong!
> for x in sequence:
>     ...
> else:
>     print("sequence is empty")
>
>
> The actually semantics of "else" is that the block is UNCONDITIONALLY run
> after the for/while loop completes, unless you jump out of the loop using
> return, raise or break. That makes it a "then" block, not "else".
>
>
>> It seems clear that it should be rather "then" than "else."  Compare
>> also "try ... then ... finally" with "try ... else ... finally".
>
> I disagree about the try block though. The semantics of the try block are:
>
> try:
>    A
> except:
>    B
> else:
>    C
> finally:
>    D
>
> (1) code block A is attempted;
>
> (2) IF an exception occurs, jump to code block B;
>
> (3) otherwise (else), no exception occurs, so jump to code block C;
>
> (4) finally run code block D on your way out, regardless of which blocks are
> executed and how you exit them.
>
>
> So I think "else" is correct here. The else block only gets called if there is
> no exception.
>
>
>> Currently, with "else", it is almost impossible to guess the meaning
>> without looking into the documentation.
>
> It is worse than that: it is easy to guess the WRONG meaning, namely that the
> else block runs when the for/while loop doesn't execute at all (the for-loop
> sequence is empty, or the while-loop condition is initially false).
>
>
>> Off course, it should not be changed in Python 3, maybe in Python 4 or
>> 5, but in Python 3 `then` could be an alias of `else` in these contexts.
>
> Unfortunately, this is almost certainly not going to happen. It would require
> adding a new keyword, and unless Guido changes his mind, he doesn't think
> this change is worthwhile.

Re-using finally would not need a new keyword and might be close enough
in meaning.

<snip>
-- 
Ben.



More information about the Python-list mailing list