[Python-ideas] except expression

Georg Brandl g.brandl at gmx.net
Thu Feb 13 16:36:43 CET 2014


Am 13.02.2014 16:28, schrieb Terry Reedy:
> On 2/13/2014 4:24 AM, Nick Coghlan wrote:
>> General comment: like Raymond, I'm inclined to favour a nice expression
>> friendly exception handling syntax, precisely because of the
>> proliferation of relatively ad hoc alternative solutions (in particular,
>> the popularity of being able to pass in default values to handle empty
>> iterables).
> 
> Leaving aside syntax, the idea makes sense to me as follows:
> 
> In Python, 'a or b' is not a just a logic operator but is generalized to 
> mean, for instance, the following: 'a, unless a is falsey, in which 
> case, b instead. The proposal is to introduce a syntax that means the 
> same with 'unless a is falsey' replaced by 'unless a raises an exception 
> of class C'. The class 'C' make 'a new_op b' inadequate.
> 
> The two alternations are related when exception C results from an input 
> that is at least conceptually falsey. Some such cases can be handled by 
> 'or' (see below). Iterators, however, are seen as truthy even when empty 
> (conceptually falsey).  And that cannot be fixed since some iterators 
> cannot know if they are empty until __next__ is called and bool is not 
> supposed to raise.
> 
>> One use case, for example, is handing IndexError when retrieving an item
>> from a sequence (which currently has no nice standard spelling, and
>> isn't amenable to the "pass in a default answer" solution because it
>> isn't a normal function call).
> 
> This is easy, if not obvious
> 
>  >>> (seq or ['default'])[0]
> 'default'
> 
> (Python's precedence rules make the parentheses optional).

Not sure if I understand correctly, but in the example above they are not.

> Doing something similar instead of dict.get is messier but conceptually 
> the same.
> 
>  >>> {}.get('key', 'default')
> 'default'
>  >>> {} or {'key':'default'}['key']
> 'default'

And this also quite certainly does not do what you intended.

Georg



More information about the Python-ideas mailing list