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

Ben Bacarisse ben.usenet at bsb.me.uk
Thu Nov 2 07:09:53 EDT 2017


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

> On Thu, 2 Nov 2017 12:50 pm, Ben Bacarisse wrote:
>
>> 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`?
> [...]
>> Re-using finally would not need a new keyword and might be close enough
>> in meaning.
>
> Reusing finally would be *completely* wrong.
>
> The semantics of `finally` is that it should be executed no matter[1] how you
> exit the previous block. E.g. if we write:
>
>
> try:
>     return 1
> finally:
>     print("exiting")
>
>
> then "exiting" is printed. Replace the return with a raise, and the same
> applies. Reusing `finally` in for and while loops would imply the similar
> behaviour:
>
>
> for i in range(100):
>     return i
> finally:
>     print("exiting")
>
>
> should print "exiting", when in fact it does not. Likewise if you replace the
> return with a break.

Sure, but your argument seemed to that else has entirely the wrong
meaning (I certainly to a double take when I have to remember what it
means) and, in that context, finally has a meaning closer to what you
want.  The problem that it carries different meanings when added to
different statements is already the case with else -- it's an
alternative to an if and not an alternative to a loop.

<snip>
-- 
Ben.



More information about the Python-list mailing list