[Python-ideas] Make return inside a finally a SyntaxError
Jan Kaliszewski
zuo at chopin.edu.pl
Sat Jul 18 14:58:21 CEST 2009
Dnia 18-07-2009 o 14:07:06 Terry Jones <terry at jon.es> napisał(a):
> I agree that having finally subsume returns and exceptions in the try
> block will at first be surprising to people, and that it can lead to
> easy-to-create but difficult-to-find bugs.
IMHO it is enough to treat it as a bug.
> But I think the current behavior is definitely for the best:
[snip]
> - If finally were to automatically propagate any exception from the try
> clause, how would you turn that off when you needed/wanted to? You'd
> soon wind up wanting another keyword, perhaps seriouslyfinally, that
> was guaranteed to be run at the very end.
No, simply:
try:
try:
...
finally:
...
except Foo:
...
> If finally propagated exceptions, what should it do if there's an
> exception raised in the finally block? It begins to get complicated.
> The primitive blanket solution is better, IMO.
But normally finally propagates exceptions. The problem is that 'return'
breakes that rule. A rule that is both logicall and intuitive.
> - Besides, if you do want a finally clause to propagate an exception from
> its try clause, that's simple as you can just store the exception
> somewhere in an except clause and then let the finally detect it and
> re-raise it, if appropriate.
Do you think about:
try:
exc = None
....
except BaseException as exc:
pass
finally
if exc:
raise exc
else:
return foobar
...?
Easy, this example is a joke. The workaround is: not to use return in
finally.
Never. (After all if you need catch an exception, you should use except).
> By keeping finally's semantics simple and resisting the temptation to
> make it more sophisticated (e.g., propagating exceptions or return
> values) you wind up with a better tool for the programmer who does
> know what they're doing.
IMHO rather the current behaviour is sophisticated, or rather surprising
and weird.
Regards,
zuo
More information about the Python-ideas
mailing list