catching exceptions in expressions

Vaclav Dvorak dvorakv at idas.cz
Thu Aug 7 20:34:15 CEST 2003


Hi,

Did I arouse nobody's interest except for Andrew? Nobody thinks catching 
exceptions inside expressions would be a cool feature to have?

Andrew Dalke wrote:
> Vaclav Dvorak:
> 
>>try: c = int(u)
>>except ValueError: c = 99
>>
>>Not enough to make me want to create a function, but enough to be
>>annoying. :-) I was thinking about something like this:
>>
>>a = int(s) except ValueError then 99
> 
> No.  In general, Python encourages new functions or
> classes over new syntax.

Well, list comprehensions were implemented, and that feature didn't even 
need anything new - not even functions, let alone syntax: "List 
comprehensions provide a concise way to create lists without resorting 
to use of map(), filter() and/or lambda." (Python Tutorial, 5.1.4.) So 
that gives me hope. :-)

> What's wrong with
> def safe_int(s, default):
[...]
> or for something more generic
> class TryCatcher:
[...]

Well, it's good when you will use than a hundred times. But when you 
need it only here and there, it's more hassle than it's worth.

>>a = int(s) or 99 if ValueError
> 
> Parse ambiguity.
> 
>   a = int(s) or 99
> 
> is valid Python today.

I'm not an expert in parsers, but wouldn't the "if" disambiguate it, as 
it's not otherwise found inside expressions? Or what if it was in 
parentheses:
 >>> a = int(s) (or 99 if ValueError)
This syntax has the advantage of not introducing any new keywords. I 
still like:
 >>> a = int(s) except ValueError then 99
somewhat better, though. But, it adds "then", and without it it wouldn't 
be so intuitive.

>>except ValueError:
>>         continue [execution on next line - my comment]
> 'continue' already has meaning in current Pythons.

That's why I chose that - no new keyword. But I retract this one, and 
the "retry" statement too. I don't really like them myself. :-)

>>Comments? Should I write a PEP? Am I missing something obvious? Has this
>>been debated a million times over already?
> 
> Feel free to write a PEP.  It won't be accepted.

Why? You're the only one who doesn't like it, so far. ;-) Of course, 
you're also the only one who voiced any opinion, so that leaves me with 
a not so huge statistical sample of one. :-)

Vaclav Dvorak  <dvorakv at idas.cz>





More information about the Python-list mailing list