Deferreds are Beautiful

   1 from twisted.internet import reactor
   2 
   3 # pedantic and gets nasty quickly
   4 
   5 def main():
   6     d = O.doLongCalculation()
   7     d.addCallback(gotResult)
   8     return d                  # the pattern you'll end up following
   9 
  10 def gotResult(result):
  11     print "result is: ", result
  12 
  13 reactor.callWhenRunning(main)
  14 reactor.run()
  15 
  16 ########################
  17 
  18 # a little nicer
  19 
  20 def main():
  21     return O.doLongCalculation().addCallback(gotResult)
  22 
  23 def gotResult(result):
  24     print "result is: ", result
  25 
  26 reactor.callWhenRunning(main)
  27 reactor.run()
  28 
  29 #######################
  30 
  31 # making things a bit more pythonic
  32 
  33 def main():
  34     def gotResult(result):
  35             print "result is: ", result
  36     return O.doLongCalculation().addCallback(gotResult)
  37 
  38 #######################
  39 
  40 # deferreds are chains
  41 
  42 def main():
  43     def gotResult(result):
  44             print "result is: ", result
  45     d = O.doLongCalculation()
  46     d.addCallback(gotResult)
  47     d.addCallback(lambda r: reactor.stop())  # throw away the result
  48     return d
  49 
  50 #####################
  51 
  52 # making our own deferreds
  53 import sys
  54 from twisted.internet import reactor, defer
  55 from twisted.python import log
  56 
  57 def sleepyCalc(message):
  58     log.msg("sleepyCalc: " + message)
  59     d = defer.Deferred()
  60     reactor.callLater(10.0, wakeyTime, d, message)
  61     return d
  62 
  63 def wakeyTime(d, message):
  64     log.msg("wakeyTime: " + message)
  65     d.callback(message)
  66 
  67 def gotResult(result):
  68     log.msg("gotResult: " + result)
  69     return "-+- gotResult -+- " + result
  70 
  71 def main(message):
  72     log.msg("main message: " + message)
  73     d=sleepyCalc(message)
  74     d.addCallback(gotResult)
  75     d.addCallback(sleepyCalc)   # hmmm...
  76     d.addCallback(gotResult)
  77     log.msg("main exit: " + message)
  78 
  79 log.startLogging(sys.stdout)
  80 
  81 reactor.callWhenRunning(main, "FIRST")
  82 reactor.callLater(2.0,main,"SECOND")
  83 log.msg("away we go")
  84 reactor.run()
  85 
  86 log.msg("bye....")