[Python-ideas] Implied try blocks

Steven D'Aprano steve at pearwood.info
Sun Mar 25 17:20:25 CEST 2012


Calvin Spealman wrote:
> 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

In this case, the "else" is not required. This could be written more simply as:

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


The else is only required when the except blocks don't exit via a return or 
raise. Otherwise, you can just continue outside of the try...except block.


> 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.

Huh? The try block is two lines, one if you don't count the "try" itself. How 
is that 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.

-1

With the current syntax, when reading code, you know when you enter a try 
block because you read "try:" just before the block begins. With your 
suggestion, the try is a booby-trap for the unwary. You're reading code, you 
read the "r = ..." line which looks like a normal line outside of a try block, 
and then *blam* you trip over the "except" and have to mentally backtrack and 
re-interpret the previous line "oh, it's actually inside a try block -- an 
invisible try block".

In my opinion, this sort of implicit change of semantics is exactly the kind 
of thing that the Zen of Python warns us against.

Your suggestion will also mask errors:

try:
     do_stuff()
except NameError:
     first_except_block()
except ValueError:
     second_except_block()
     and_another_line()
and_a_third_line()  # oops, I forgot to indent
except TypeError:
     ...


Currently, this will be a SyntaxError. With your suggestion, it will silently 
do the wrong thing.


-- 
Steven




More information about the Python-ideas mailing list