[Python-3000] Exception Expressions
Brett Cannon
brett at python.org
Thu Aug 31 20:20:20 CEST 2006
On 8/31/06, Calvin Spealman <ironfroggy at gmail.com> wrote:
>
> I thought I felt in the mood for some abuse today, so I'm proposing
> something sure to give me plenty of crap, but maybe someone will enjoy
> the idea, anyway.
Never hurts too much to try, huh? =) Plus it gives me a break from my
work.
This is a step beyond the recently added conditional
> expressions. I actually made this up as a joke, explaining at which
> point we would have gone too far with branching logic in an
> expression. After making the joke, I was sad to realize I didn't mind
> the idea and thought I'd see if anyone else doesn't mind it either.
>
> expr1 except expr2 if exc_type
>
> For example, given a list, letters, of ['a', 'b', 'c'], we would be
> able to do the following:
>
> print letters[7] except "N/A" if IndexError
So this feels like the Perl idiom of using die: ``open(file) or die`` (or
something like that; I have never been a Perl guy so I could be off).
This would translate to something along the lines of:
>
> try:
> _tmp = letters[7]
> except IndexError:
> _tmp = "N/A"
> print _tmp
>
> Obviously, the except in an expression has to take precedence over if
> expressions, otherwise it would evaluate '"N/A" if IndexError" first.
> The syntax can be extended in some ways, to allow for handling
> multiple exception types for one result or different results for
> different exception types:
>
> foo() except "Bar or Baz!?" if BarError, BazError
> foo() except "Bar!" if BarError, "Baz!" if BazError
>
> Other example use cases:
>
> # Fallback on an alternative path
> open(filename) except open(filename2) if IOError
>
> # Handle divide-by-zero
> while expr != "quit":
> print eval(expr) except "Can not divide by zero!" if
> ZeroDivisionError
> expr = raw_input()
>
> # Use a cache when an external resource timesout
> db.get(key) except cache.get(key) if TimeoutError
>
> Only very basic exception handling would be useful with this syntax,
> so nothing would ever get out of hand, unless someone wasn't caring
> about their code looking good and keeping good line lengths, so their
> code probably wouldn't look great to begin with.
The problem I have with this whole proposal is that catching exceptions
should be very obvious in the source code. This proposal does not help with
that ideal. So I am -1 on the whole idea.
-Brett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20060831/602811a4/attachment.html
More information about the Python-3000
mailing list