[Python-ideas] except expression

Andrew Barnert abarnert at yahoo.com
Thu Feb 20 02:34:26 CET 2014


From: Ethan Furman <ethan at stoneleaf.us>

Sent: Wednesday, February 19, 2014 5:05 PM


> Subject: Re: [Python-ideas] except expression
> 
> On 02/19/2014 05:00 PM, Chris Angelico wrote:
>>  On Thu, Feb 20, 2014 at 11:15 AM, Ethan Furman <ethan at stoneleaf.us> 
> wrote:
>>>  which would be converted to (using Nick's notation):
>>> 
>>>  result = 1/x except ZeroDivisionError -> NaN
>>> 
>>>  result = some_func(value1, value2) except SomeError -> 42
>> 
>>  These two I strongly support (colon or arrow, either way).
>> 
>>>  os.unlink(some_file) except OSError -> None
>> 
>>  This one, not so much. You're using os.unlink(some_file) as a
>>  statement, ignoring its return value. Changing its return value to
>>  None in the case of an exception isn't exactly what you're trying 
> to
>>  do. Yes, it does make for a one-liner, where the full form takes two:
>> 
>>  try: os.unlink(some_file)
>>  except OSError: pass
>> 
>>  but I'm not sure that it's the right way to do things.
> 
> 1) It could be used inside a function call or assigned to a variable;

Why would you use an expression that always evaluates to None (with or without an except handler that also always evaluates to None) in a function call or assignment, or really anywhere else but a simple expression statement?

> 2) We're creating a new expression type -- it'll be valid anywhere an 
> expression is valid, even all by itself.  e.g. `1 
> + 2` is valid, even though nothing is done with the result.


Sure, it's valid, but it's also useless (except in the interactive interpreter, where something _is_ done with the result), so we don't need to add syntax to make it more powerful. Twice as powerful as useless is still useless.

So, while there's no need to actually ban "os.unlink(some_file) except OSError: None", it doesn't make a good argument for the PEP.


More information about the Python-ideas mailing list