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

Nick Coghlan ncoghlan at gmail.com
Sat Jul 18 16:37:33 CEST 2009


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
> 
> def f():
>   try:
>     raise Exception()
>   finally:
>     return 4
> 
> 
> Michael Foord

I just remembered the case where I found it convenient to exploit this
behaviour for a quick and dirty script where I wanted as much of a list
that worked as I could get before one of the operations threw an
exception or I ran out of items:

def f(iter):
  s = []
  try:
    for x in iter:
      s.append(op(x))
  finally:
    return s

The fact that that would be better rewritten using a narrower except
statement (see postscript below) doesn't change the fact that it got the
job done (which was what was important at the time).

Cheers,
Nick.

P.S. The "better" approach to the above situation:

def f(iter):
  s = []
  try:
    for x in iter:
      s.append(op(x))
  except RuntimeError:
    pass
  return s

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list