[Python-ideas] except expression

Rob Cliffe rob.cliffe at btinternet.com
Fri Feb 14 13:33:09 CET 2014


I propose the syntax

     x = try entries[0] except IndexError: None

Advantages:

(1) Similar to the current try ... except syntax, so meaning immediately 
obvious.

(2) Allows all the current (and future??) syntax of except clauses:
     x = try get_it() except IOError as e: e.errno
     x = try get_it() except (OSError, IOError): None
     x = try entries[0] except NameError: ProgramError[1] except 
IndexError: None

(3) Unambiguous: in the last example the second "except" traps an 
IndexError that occurs during the evaluation of "entries[0]", not during 
the evaluation of "ProgramError[1]" (the latter would be written with a 
second "try" before "ProgramError[1], not that I would recommend doing 
it).  An "except" refers to the expression following the nearest 
preceding "try".  I.e. there is no "dangling except" problem.

(4) Straightforward to parse.  The leading "try" immediately tells the 
parser what to expect.  And the "except"s and colons are unambiguous 
delimiters.  Ditto for a human reader.

(5) No new keyword, or strained use of an existing keyword, needed.

It would be illegal to have a "try" expression without at least one 
"except", just as is it currently illegal to have a "try" statement 
without at least one "except" or "finally".

Rob Cliffe


On 13/02/2014 23:37, Greg Ewing wrote:
> Amber Yust wrote:
>> Actually. What if we just reused 'try'?
>>
>>     foo = bar() except BazException try 'qux'
>
> This suggests that trying 'qux' may somehow fail to work,
> which is not the intended meaning at all.
>



More information about the Python-ideas mailing list