2009/7/18 Steven D'Aprano
<steve@pearwood.info>
On Sat, 18 Jul 2009 09:41:10 am Michael wrote:
> Here are two examples of why allowing return inside a finally block
> is a bad idea:
>
> def f():
> try:
> return 3
> finally:
> return 4
Given that the finally block is guaranteed to run after exiting the try
block, I don't see anything objectionable about that. Surprising,
perhaps, possibly even an artifact of the CPython implementation, but
why is it a "bad idea" that needs to be protected against?
It's arbitrary - and constructs with arbitrary interpretations are generally not a *good* thing at the very least. It also makes it harder to read code, where a return in a try:... finally block may not do anything.
> def f():
> try:
> raise Exception()
> finally:
> return 4
That's no weirder than:
def f():
try:
raise Exception()
except Exception:
return 4
or:
def f():
try:
raise Exception()
except Exception:
pass
return 4
It is much weirder. In the case of explicitly using an except you are catching the error and choosing not to propagate it. In a finally where the normal semantics are that the exception is re-raised the return silently circumvents that.
Michael
--
Steven D'Aprano