[Python-ideas] Make return inside a finally a SyntaxError

Stephen J. Turnbull stephen at xemacs.org
Sat Jul 18 15:20:48 CEST 2009


Michael Foord writes:

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

But that's true of *all* code in a try block:

    def foo():
        try:
            x = 42
        finally:
            x = "gotcha!"
        return x

or

    def bar():
        try:
            x = some_function_normally_returning_42()
            return x
        except Exception:
            return "didn't see that coming!"

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

AFAICS "finally" is a restriction of call-with-current-continuation.
Ie, the block is "spliced into" the control flow at the exit, and if
control "flows off the end" of the finally block, then we go back to
doing what we were about to do (return, propagate an exception).  But
if the block exits otherwise, then we don't.  What's "weird" about
that?

Eg, the finally block could do something that itself raises an
exception.  If so, I guess you would say that instead of dealing with
the "new" exception, we should blow it off and reraise the original
exception?







More information about the Python-ideas mailing list