[Python-ideas] try-else without except or finally

Chris Kaynor ckaynor at zindagigames.com
Mon Nov 14 21:04:30 CET 2011


On Mon, Nov 14, 2011 at 11:34 AM, Matt Joiner <anacrolix at gmail.com> wrote:
> To be fair it's not a new construct, it's loosening the constraints on
> an existing one.
>
> else has the same use as in the for and while compound statements:
> It's executed if the first block completes "successfully". An
> exception being thrown in a try block, cancels execution of the "else"
> block, the same way as "break" in the for and while statements.
>
> I have a problem with the idea now in that:
>
> try:
>    a
> else:
>    b
>
> is the same as:
>
> try:
>    a
>    b
> else:
>    pass
>
> and even:
>
> try:
>    pass
> else:
>    a
>    b
>
> in every possible interpretation. This isn't possible with if, for,
> while, try/except, and try/finally compound statements, all of which
> alter the meaning in *some* way.

If you add finally, the else clause still maintains the same semantics
in a try statement - only except statements modify the equivalence of
else:
try:
 a
else:
 b
finally:
 c

is the same as:
try:
 a
 b
else:
 pass
finally:
 c

and

try:
 pass
else:
 a
 b
finally:
 c

What changes with the finally is that you cannot move the "b"
statement out of the try completely. Without the finally clause, the
following are the same:

try:
 a
else:
 b

try:
 a
b

a
b




Similar behavior can be shown with for: else and while: else, if there
is no break (I'm only showing a while statement below, however it
converts exactly to a for statement):
while a:
 b
else:
 c

is the same as:
while a:
 b
c

so long as "b" does not include a break statement.



>
> So I maintain that the else block could be made allowable even without
> an except block, but it would be purely for convenience. I don't think
> it's worth it anymore.

While it is redundant to allow else without except, I would agree that
it should be allowed for the same reason that else is allowed on for
and while without a break. The alternative would be to make the later
illegal. Either seems reasonable, however the former maintains
backwards compatibility, while the later breaks it.

>
> Cheers all for consideration.



More information about the Python-ideas mailing list