[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 20 05:33:00 CET 2014


On Thu, Feb 20, 2014 at 3:17 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Here's another idea:
>
>    result = 1/x except {ZeroDivisionError: NaN}
>
> You can read the part in {...} as a dictionary
> (although it needn't be implemented that way)
> so it doesn't use colons in any way they aren't
> being used already.

If it even might be implemented that way, the default clause(s) would
have to be eagerly evaluated. I'd like to avoid that, for several
reasons:

1) In a try/except statement, the suites are parsed "try first, then except".
2) Fixing this difference with dict.get() is a valuable improvement -
see the main Proposal section of the PEP.
3) Performance would be unnecessarily impacted by evaluating all the
default values.
4) It makes good sense for a conditionally-executed section to be
allowed to depend on its condition. Just as you can write "1/x if x
else NaN", confident that it won't evaluate "1/x" unless x, you should
be able to write "1/x except ZeroDivisionError:
ask_user_to_choose(NaN, 0, Inf)" and depend on the user being asked
only when the division by zero happens. Restricting this would force
people to go back to the statement form, while leaving the code
looking like it should be converted.

Conversely, if you retain lazy evaluation while using a very dict-like
notation will confuse people enormously. This would be... a dictionary
that maps exception types to unevaluated expressions? Why can't I use
one of those somewhere else!!!

ChrisA


More information about the Python-ideas mailing list