[Python-3000] Exception Expressions (original) (raw)
Calvin Spealman ironfroggy at gmail.com
Thu Aug 31 19:42:57 CEST 2006
- Previous message: [Python-3000] have zip() raise exception for sequences of different lengths
- Next message: [Python-3000] Exception Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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. 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_typeFor example, given a list, letters, of ['a', 'b', 'c'], we would be able to do the following:
print letters[7] except "N/A" if IndexErrorThis would translate to something along the lines of:
try:
_tmp = letters[7]
except IndexError:
_tmp = "N/A"
print _tmpObviously, 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 BazErrorOther 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 TimeoutErrorOnly 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.
If there is any positive response I'll write up a PEP.
- Previous message: [Python-3000] have zip() raise exception for sequences of different lengths
- Next message: [Python-3000] Exception Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]