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

Steven D'Aprano steve at pearwood.info
Sat Jul 18 02:59:57 CEST 2009


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?



> 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


-- 
Steven D'Aprano



More information about the Python-ideas mailing list