[Python-ideas] except expression

Yury Selivanov yselivanov.ml at gmail.com
Thu Feb 20 01:22:33 CET 2014


On 2/15/2014, 11:04 PM, Chris Angelico wrote:
> [snip]
> Alternative Proposals
> =====================
>
> Discussion on python-ideas brought up the following syntax suggestions::
>      value = expr except default if Exception [as e]
>      value = expr except default for Exception [as e]
>      value = expr except default from Exception [as e]
>      value = expr except Exception [as e] return default
>      value = expr except (Exception [as e]: default)
>      value = expr except Exception [as e] try default
>      value = expr except Exception [as e] continue with default
>      value = default except Exception [as e] else expr
>      value = try expr except Exception [as e]: default
>      value = expr except Exception [as e] pass default

How about adding a new keyword?

If we add new 'raises' keyword, then we can have the following
new syntax:

# set 'value' to 42 if len(a) < 10
# or else, return a[10]
value = 42 if a[10] raises IndexError

# set 'value' to 42 if len(a) < 10
# or else, return 'spam'
value = 42 if a[10] raises IndexError else 'spam'

# same as above but if a[10] raises anything
value = 42 if a[10] raises

# another example
foo(None if dct['key'] raises)


This syntax doesn't provide:
- finally statement replacement;
- handling multiple exceptions;
- rerising exception;
which I think is a good thing. No need to complicate this
syntax.


Pros:
- easy to read (like English or pseudocode)
- looks like existing 'expr if expr else expr' syntax

Cons:
- adds a new keyword


Yury


More information about the Python-ideas mailing list