try:else: w/o except: - why not?
Jeff Epler
jepler at unpythonic.net
Mon Mar 31 19:21:02 EST 2003
Because your proposed try:else: would have an implied bare except, and
because a bare (unqualified) except is generally a bad thing, I'd rather
not see this implemented.
I first thought that
try:
abc
else:
def
might be equivalent to
try:
abc
except:
raise
else:
def
but of course that's already writable, as
abc
def
so that's obviously not what you're asking for.
You didn't give an example. The first thing I thought of was a
construct like this:
try:
x[i]
else:
x[i] += 1
(as a translation of "if x.has_key(i): x[i] += 1"). But if you actually
wrote this out, you'd really want to say
try:
x[i]
except (KeyError, IndexError):
pass
else:
x[i] += 1
so as to avoid incorrect suppression of any other exception that might
accidentally be raised by the 'try' block. (In interactive programs,
KeyboardInterrupt is the common example)
So since the price of writing the eqiuvalent code today is low (two lines),
the price of adding the feature is an easy way to implicltly use a
construct that is yucky, and I can't immediately think of a good use for
it, I don't think it's a good addition to the language. Relevant items
from the Zen of Python:
Explicit is better than implicit.
Simple is better than complex.
Special cases aren't special enough to break the rules.
Errors should never pass silently.
In the face of ambiguity, refuse the temptation to guess.
Jeff
More information about the Python-list
mailing list