On Tue, Dec 12, 2017 at 7:39 PM, Michel Desmoulin
Le 29/11/2017 à 19:02, Barry Warsaw a écrit :
On Nov 29, 2017, at 12:40, David Mertz
wrote: I think some syntax could be possible to only "catch" some exceptions and let others propagate. Maybe:
val = name.strip()[4:].upper() except (AttributeError, KeyError): -1
I don't really like throwing a colon in an expression though. Perhaps some other word or symbol could work instead. How does this read:
val = name.strip()[4:].upper() except -1 in (AttributeError, KeyError)
I don’t know whether I like any of this <wink> but I think a more natural spelling would be:
val = name.strip()[4:].upper() except (AttributeError, KeyError) as -1
which could devolve into:
val = name.strip()[4:].upper() except KeyError as -1
or:
val = name.strip()[4:].upper() except KeyError # Implicit `as None`
I would *not* add any spelling for an explicit bare-except equivalent. You would have to write:
val = name.strip()[4:].upper() except Exception as -1
Cheers, -Barry
I really like this one. It's way more general. I can see a use for IndexError as well (lists don't have the dict.get() method).
Also I would prefer not to use "as" this way. In the context of an exception, "as" already binds the exception to a variable so it's confusing.
What about:
val = name.strip()[4:].upper() except Exception: -1
That happens to be the exact syntax recommended by PEP 463 (modulo some distinguishing parentheses). https://www.python.org/dev/peps/pep-0463/ ChrisA