On 06/08/2020 12:39, Jonathan Grant wrote:
Hey all,
Instead of writing this:
```
try:
return my_dict[“a”][“b”][“c”][“d”]
except:
return “some default”
Please, say "except KeyError:" (or whatever). A bare "except" is
dangerous, as it will catch *all* exceptions, including totally
unexpected ones (making debugging harder).
```
Or this
```
return my_dict.get(“a”, {}).get(“b”, {}),get(“c”, {}).get(“d”, “some
default”)
```
I propose we allow for an inline exception handler, like `eor`:
```
return my_dict[“a”][“b”][“c”][“d”] eor “some default”
```
This works very similar to what we already have with `or`, and makes
code much more compact and readable.
--
As Chris says, this is similar to the rejected PEP 463
"Exception-catching expressions".
The main difference IMO is that in PEP 463 you must specifiy the
exception(s) to be caught. E.g.
return (my_dict[“a”][“b”][“c”][“d”] except KeyError: "some default")
*Not* specifying the exception(s), as in your proposal, is very
dangerous (just like a bare "except" clause). E.g. if you could write
return 1/MisspeltVariableName except "You divided by zero" # No you
didn't, you got a NameError.
(Unless your proposal was specifically to catch just KeyError (or some
other fixed, small set of exceptions) which would greatly limit its
usefulness. I assume it wasn't.)
Best wishes
Rob Cliffe
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/BXZKP5LFBSYINMA7PAJ66XZJPO6NDVLN/
Code of Conduct: http://python.org/psf/codeofconduct/