[Twisted-Python] ANN: deferred howto/tutorial

Tommi Virtanen tv at twistedmatrix.com
Sun Oct 24 02:08:38 MDT 2004


stefan wrote:
> discussion on that in the docs would be great. I've attached an example 
> of my style, maybe someone with a different style can rewrite the 
> example and comment on pros and cons?
> ---------------------------------------------------------------
> class X:
>     ...
>     def y(self):
>         # do some method initialisation
>         ...
>         # callbacks
>         def oneBack(result):
>               # extract someParams out of result
>               ...
>               return self.somethingDeferred().addCallback(twoBack, 
> someParams)
> 
>         def twoBack(result, someParams):
>               return "Foo" or raise Bar()
> 
>         return self.somethingDeferred().addCallback(oneBack)
> ---------------------------------------------------------------

I still prefer

d = self.somethingDeferred()
d.addCallback(oneBack)
return d

mostly because I tend to vomit when I see moshez write
something like

return self.somethingDeferred(foo, bar, baz, thud,
     quux).addCallback(oneBack, bar, baz,
     ).addErrback(twoBack, baz).addBoth(threeBack,
     foo)

Also, I tend to use nested functions for small and mostly
trivial things, like

def firstOne((a,b)):
     return a

and class-level functions for anything more complicated.
Whenever it is not absolutely clear from the context that
a function is a callback, I prefix the name with "cb", and
if it's a class-level function, I start the name with an
underscore to mark it an implementation detail.

class X:
     ...

     def _cbOneBack(self, result):
           ...
           d = self.somethingDeferred()

           def format(result, someParams):
                 return "Result is %r, %r" % (result, someParams)
           d.addCallback(format, someParams)

           return d

     def y(self):
         ...
         d = self.somethingDeferred()
         d.addCallback(self._cbOneBack)
         return d




More information about the Twisted-Python mailing list