[Python-ideas] except expression

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Feb 14 00:26:01 CET 2014


Terry Reedy wrote:

>  >>> (seq or ['default'])[0]
> 'default'
> 
> (Python's precedence rules make the parentheses optional).

Um, no, they don't:

 >>> seq = ['a']
 >>> (seq or ['default'])[0]
'a'
 >>> seq or ['default'][0]
['a']

In any case, this only works for an extremely special case
(an index of 0), and can hardly be seen as an alternative
to the proposed except-expression.

>>>> {}.get('key', 'default')
> 'default'
>>>> {} or {'key':'default'}['key']
> 'default'

This is an even *more* special case, since it only works
if you know that the only way the dict can possibly fail
to contain the key is if it's completely empty.

-- 
Greg


More information about the Python-ideas mailing list