[Twisted-Python] Having some kind of "finally" clause

Jean-Paul Calderone exarkun at divmod.com
Mon Sep 22 09:23:31 EDT 2008

On Mon, 22 Sep 2008 15:12:53 +0200, Vincent Bernat <bernat at luffy.cx> wrote:
>I would like to do something like this with Twisted:
> x.someoperations()
> x.otheroperations()
> x.close()
>I could do something like this :
>d = open_and_get_x()
>return d
>Each callback would return x to let the next callback proceed it. However,
>if there is an error, I have no "x" to close in "closeAndReRaiseIfError".
>How can I do that?

There are a lot of ways.  You could make x an attribute of a shared object,
or you could close over it in the first callback to create the "finally"
handler, or you could pass it along as an argument to the `addBoth´ call
(again, in the first callback).

Notice that there's a slight difference between the two code examples you
gave.  The first won't close x in response to errors from `x.open()´, but
`closeAndReRaiseIfError´ will be called even for errors from `open_and_get_x´.
If you only add the finally handler in the first callback attached to `d´,
then this difference goes away.


>Twisted-Python mailing list
>Twisted-Python at twistedmatrix.com

More information about the Twisted-Python mailing list