[Python-ideas] Single line single expression try/except syntax

Alex Shafer ashafer at pm.me
Sun Jan 27 06:52:34 EST 2019


Hello,

I'd like to discuss an idea I had to shorten the syntax for the common case of having a try/except/finally/else block where all of the following conditions are met:

* There is only one except block, no finally or else
* The exception is not captured in the except block, i.e. `except KeyError:` not `except KeyError as e:`
* The contents of the except block is only a single expression
* Perhaps, the expression starts with a control word such as pass, break, continue, return, raise. As it happens, everything useful I can think to do with this right now currently uses these. Unclear to me if this should be a requirement.

The syntax I envisioned would be something like the following:

try on ValueError pass:
    some_list.remove('value')
I'm not at all attached to the `on` token specifically, but I think something is necessary there.
Other examples:

def func():

    try on KeyError, ValueError return False:

        dict_of_lists['key'].remove('value')

key = 'foo'

try on KeyError raise MyApplicationError(f'{key} not found'):

    a_dict[key]



for i in range(100):

    try on TypeError continue:

        a_list[i] += 1

        etc()

I realize this could be accomplished with context managers, but that seems like overkill to simply throw away the exception, and would increase the overall required code length.
Thanks for your input!
Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190127/1e9a262b/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 509 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190127/1e9a262b/attachment-0001.sig>


More information about the Python-ideas mailing list