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

Georg Brandl g.brandl at gmx.net
Sat Jul 18 11:52:50 CEST 2009


Michael schrieb:
> Here are two examples of why allowing return inside a finally block is  
> a bad idea:
> 
> def f():
>    try:
>      return 3
>    finally:
>      return 4
> 
> def f():
>    try:
>      raise Exception()
>    finally:
>      return 4

I've been bitten by this as well, putting all my cleanup code including the
return unthinkingly into the finally clause.  It took a while of debugging
to find this instance, and realize that the behavior is correct if unexpected.

On the other hand, there may be cases where it is actually the most concise
way to express what you want.  I guess it's like the parameter defaults "wart":
once you've fallen over it once, you'll not make the same mistake again,
and use it when it's correct to do so.

However, why break and continue behave inconsistently, I can't see right now.
Maybe continue needs some more trickery implementation-wise?

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list