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

Terry Reedy tjreedy at udel.edu
Tue Nov 15 01:53:05 CET 2011


On 11/14/2011 3:04 PM, Chris Kaynor wrote:

> While it is redundant to allow else without except,

It is as redundant as allowing an 'else' without 'if', which is also not 
allowed. If fact, the exactly meaning of 'else' depends on what it is 
subordinate to -- 'if', 'while', 'for', or 'except'. So a bare 'else' 
would be ambiguous as to exact meaning, though the effect of 'pass' 
would be the same.

The construct analogous to if...elif...else is except...except...else. 
After the first 'except', 'except' is an abbreviation for 'else-except', 
just as 'elif' is an abbreviation for 'else-if'.

Try-else is *not* analogous to if-else. 'Try' is not a conditional. The 
next line *always* executes (successfully or not). 'Try' only means 
'prepare a context for special treatment of exceptions'. One special 
treatment is to execute code only if there is an exception (after it is 
caught). The other is to execute code even if there is an exception.

> I would agree that it should be allowed for the same reason
> that else is allowed on for and while without a break.

One is also allowed to write dubious code in numerous other ways:

if <some condition that can never be true>: body
if <some condition that must always be true>: body
while <condition>: break; body
while <condition>: body; break
a=1; a=2
...

So what? The fact that a language spec, especially one limited to a 
context-free LL(1) grammar, allows one to write dead or irrelevant code 
in several ways is *not* a reason to add another, especially one that is 
logically incoherent and *always* useless, not just sometimes.

The CPython  parser and compiler are written to run reasonably fast. 
Third-party code checkers raise warnings for things they can catch with 
more extended analysis.

Anyway, there is no analogy between 'try' and 'while' or 'for'. Both of 
the latter are 'if' statements augmented with a hidden goto to produce 
looping. The 'else' is subordinate to the 'if' part.  Both can be 
terminated early by 'break', which is only allowed in loops. None of 
this has anything to do with 'try'.

> The alternative would be to make the later illegal.

Try writing a Python-legal grammar that does that;-).

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list