[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 13 04:38:24 CET 2014


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.
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.

ChrisA


More information about the Python-ideas mailing list