[Python-ideas] Implied try blocks

Calvin Spealman ironfroggy at gmail.com
Sun Mar 25 16:15:05 CEST 2012


Given that for some time the try/except/else form is standard and
encouraged, I've found the following pattern really common in my code:

try:
    r = some_single_statement()
except TypeError:
    print "oh no!"
    raise OhNoException()
else:
    p = prepare(r)
    print "I got", p

Where the try block ever doing more than one thing feels dangerous or sloppy,
because I want to make sure I know exactly where the exception comes from.
The else block becomes the long tail and the try is just the head. This makes
the try block itself seem heavy.

What if we allowed this to be implied and except/else blocks bound to
the previous
statement? A try block would be an optional form, and mostly left for
multi-block try's

r = some_single_statement()
except TypeError:
    print "oh no!"
    raise OhNoException()
else:
    p = prepare(r)
    print "I got", p

I think it reads acceptably. With a try: block your eye leads up right
to that one statement.
There is no ambiguity to deal with, that I can tell. I'm not sure if
this is a great idea,
but I don't dislike it.

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy



More information about the Python-ideas mailing list