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

Terry Reedy tjreedy at udel.edu
Thu Nov 10 23:10:24 CET 2011


> On Thu, Nov 10, 2011 at 10:53 AM, Guido van Rossum<guido at python.org>  wrote:
>> On Thu, Nov 10, 2011 at 5:35 AM, Rob Cliffe<rob.cliffe at btinternet.com>  wrote:
>>> "except: raise" makes it explicit that an exception is to be propogated.
>>>   Far from being pointless it makes the code much more readable.  "Explicit
>>> is better than implicit."
>>
>> +1. Nobody's going to understand try...else... on first reading.

Perhaps because an else: in this context, without being subordinate to 
anything, would be irrelevant, equivalent to 'pass' or, more exactly, 
'if True:'.

Else is always subordinate to some conditional clause$. The 'if' clause 
for try statements is the first except clause, not the try header: 
'except x:' means something like 'if raised(x):' (since the 
corresponding try setup statement). The else clause is actually an elif 
clause: 'else:' means 'elif nothing_raised():'.

To illustrate, the C equivalent of

try:
   a = b/c
except ZeroDivisionError:
   print('bah')
else:
   print('hooray')

would be (minus the punctuation that I have forgotten) something like

errno = 0  /* setup error detection mechanism, just as try: does */
a = b/c
if errno == EZERODIV  /* or whatever it is */
   printf('bah')
elif errno == 0  /* ie, no error since setup */
   printf('hooray')

  I suspect Python *could* have been defined to require 'except 
NOEXCEPTION:' instead of 'else:' by initializing an internal exception 
variable (equivalent to C's errno) with NOEXCEPTION. Howver, 'else:' is 
definitely nicer (just as normal 'else:' is equivalent to and nicer than 
'elif True:').


$ A for loop is equivalent to a while loop with condition z"iterator 
(initially iter(iterable)) is not empty". Break and continue have the 
same meaning as in while loops.

Any while loop, such as

while c:
   x
else:
   y

is equivalent to an if statement with goto. In 
'Python-with-label-and-goto' the above would be the same as

label start_loop
if c:
   x
   goto start_loop
else:
   y

So: in Python (as elsewhere), 'else' clauses always follow one or more 
headers that specify conditional execution and only trigger when the 
previous condition or conditions are false. Their use in various 
statement types is consistent and logically correct.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list