[Twisted-Python] ANN: deferred howto/tutorial

stefan fu at donfu.com
Sat Oct 23 16:40:40 EDT 2004


> So what i did was write a tutorial on my deferred enlightenment...(pun
> intended?)

My way to grok deferreds was a detoured as well, when I started using 
twisted two months ago.
First thing, I tried to avoid them. Until I reached a point where you 
wouldn't get to all that candy functionallity witouth using them. Then 
I found twisted.flow and thought this concept was much clearer to me. I 
used it and my code somehow worked. Until it didn't work anymore, and 
then I was screwed. Someone told me, I should rather use defgen, which 
I did. But when exeptions vanished in looping yields that yielded 
loops, I was lost again. At that point I rewrote the whole database 
backend using plain old deferreds. And then I understood them. Because 
they are simple and elegant, once you get the concept.

What I missed in the docs, was a bit more concrete examples and styles 
of how to use deferreds in slightly more complex code. Most of the code 
is not class based, and you don't find branching or looping code that 
deals with deferreds. Both is not terribly difficult, but at first you 
really don't dare to know how a loop with deferreds will looks like.

What I also would like to see is some coding practices of how to style 
deferred code. I got used to inner functions in class methods, which 
for me looks clearest, but I'm sure there are other practices. A short 
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)
---------------------------------------------------------------

regards
stefan.





More information about the Twisted-Python mailing list