Return twice in a python function

1.py:

  def foo():
   try:
    return 'foo'
   finally:
    return 'bar'


  print foo()

2.py

  def foo():
   try:
    return 'foo'
   finally:
    print 'bar'


  print foo()

The result is shocking...

  $ python 1.py 
  bar
  $ python 2.py 
  bar
  foo

I think this particular behavior is well abused in WSGI

two cents:

to quote the official doc:

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.
In a generator function, the return statement is not allowed to include an expression_list. In that context, a bare return indicates that the generator is done and will cause StopIteration to be raised.

As to yield:

As of Python version 2.5, the yield statement is now allowed in the try clause of a try ... finally construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.

Black magic!

Comments