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

Michael Foord fuzzyman at gmail.com
Sat Jul 18 13:42:30 CEST 2009


2009/7/18 Steven D'Aprano <steve at 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
http://www.ironpythoninaction.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090718/f5b0e282/attachment.html>


More information about the Python-ideas mailing list