[Python-ideas] except expression
Terry Reedy
tjreedy at udel.edu
Thu Feb 13 14:38:32 CET 2014
On 2/13/2014 5:10 AM, M.-A. Lemburg wrote:
> On 13.02.2014 10:24, Nick Coghlan wrote:
>> General comment: like Raymond, I'm inclined to favour a nice expression
>> friendly exception handling syntax, precisely because of the proliferation
>> of relatively ad hoc alternative solutions (in particular, the popularity
>> of being able to pass in default values to handle empty iterables).
>
> Here's a variant the resembles the code you'd write in a helper
> function to achieve the same thing, only stripped down somewhat:
>
> x = something() except ValueError return default_value
>
> def try_something():
> try:
> return something()
> except ValueError:
> return default_value
>
> x = something() except ValueError as exc return exc.message
In Python 3 that would be
x = something() except ValueError as exc return exc.args[0]
> def try_something():
> try:
> return something()
> except ValueError as exc
> return exc.message
>
> Obviously, having a keyword "use" would make a better fit :-)
>
> x = something() except ValueError use default_value
x = something() except ValueError as exc try exc.message
Try otherthing instead of something. That could even be chained
x = something() except ValueError as exc continue with exc.message
Instead of breaking due to the exception; 'with' could be left out.
x = something() except ValueError as exc pass exc.message
Pass expression back to x or consumer of expression.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list