try...finally is more powerful than I thought.

Michael Hudson mwh at python.net
Fri Nov 7 08:07:40 EST 2003


Brian Kelley <bkelley at wi.mit.edu> writes:

> def res():
>      try:
>          a = 1
>          return
>      finally:
>          print "do I get here?"
> 
> res()
> 
> outputs "do I get here?"
> 
> I can't say why I didn't really expect this, the control flow is a
> little wierd as the function isn't really returning at the "return"
> statement but executing the bit in the finally: block and then
> returning.  I think :)
> 
> That being said, I like it a lot.  How is this working internally?
> Does the finally get executed when try code block goes out of scope?
> This would happen during a return or an exception which could explain
> the magic.

Internally, and locally to one function, leaving via returning a value
and raising an exception is pretty similar.

Cheers,
mwh

-- 
  I'm not sure that the ability to create routing diagrams 
  similar to pretzels with mad cow disease is actually a 
  marketable skill.                                     -- Steve Levin
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html




More information about the Python-list mailing list