[Python-ideas] except expression

spir denis.spir at gmail.com
Thu Feb 13 12:25:07 CET 2014


On 02/13/2014 04:38 AM, Chris Angelico wrote:
> On Thu, Feb 13, 2014 at 2:20 PM, Amber Yust <amber.yust at gmail.com> wrote:
>> Ah, that's a good point (the two-directionality of yield had slipped my
>> mind). I had considered suggesting return instead of yield, which wouldn't
>> have that problem, but it felt like return would be more confusing to see in
>> a context where it doesn't actually return from the enclosing scope.
>
> Yeah. I like the parallel with "get this unless it's empty in which
> case use this default", but the 'or' keyword is already a bit awkward
> there, so I don't want to advocate that.
>
> name = input("Name [Anonymous]: ") or "Anonymous"
> phone = addressbook[name] except KeyError or "Unknown"
>
> It's a nice parallel, but doesn't read well (plus, >> KeyError or
> "Unknown" << is already an expression).
>
> +1 on the feature but it definitely needs a syntax that makes sense.

I don't see any issue with:
     phone = addressbook[name] except "Unknown" if KeyError
     phone = addressbook[name] except "Unknown" if KeyError as e
It is similar in syntax and meaning with if-expressions, with the first keyword 
'except' obviously making all the difference we need.

[By the way, this shows that:
	x = b if cond else a
should really be:
	x = a else b if cond
The difference being that the standard case is expressed first, the exceptional 
one being then introduced as an special variant.]

In some languages (eg Lua) there is no difference between absent values (vars, 
attributes, items...) because of an arror (they should be there, in python we 
get an exception) and optional values (in python there is None for this 
meaning). In the latter case, presence of absence both are valid alternatives in 
the app's logic. Such a lack of distinction (in Lua, both yield nil) is very 
bad, indeed, but combined with "permissive" logical expressions (in which 
operands may not be logical, and result value as well) allows:
     phone = addressbook[name] or "Unknown"

However, this idiom is mainly common in lua because there are no standard param 
values (defaults):
     Shape.fill = function (shape, color)
           color = color or black
           ...
      end
This also shows that the cases in python were we do need such an idiom are 
pretty rare, all in all: should we bother?

> Of course, it could be done as a function call:
>
> def catch(callme, catchme, returnme):
>    try:
>      return callme()
>    except catchme:
>      return returnme
>
> phone = catch(lambda: addressbook[name], KeyError, "Unknown")
>
> but that's *really* clunky.

I'd like such a solution if builtin (for it to be standard, thus widely shared 
in python code) and did not force writing a lambda.

d


More information about the Python-ideas mailing list