Search code examples
pythonpython-2.7twistedautobahn

Why does this python autobahn code need to use the 'yield' keyword?


Why does this python autobahn example code uses yield sleep(1) and not simplysleep(1) ?

class Component(ApplicationSession):
       """
   An application component that publishes an event every second.
   """

   @inlineCallbacks
   def onJoin(self, details):
      print("session attached")
      counter = 0
      while True:
         print(".")
         self.publish('com.myapp.topic1', counter)
         counter += 1
         yield sleep(1)

if __name__ == '__main__':
   from autobahn.twisted.wamp import ApplicationRunner
   runner = ApplicationRunner("ws://127.0.0.1:8080/ws", "realm1")
   runner.run(Component)

Solution

  • Because Python's standard library sleep will block the Twisted reactor, whereas Autobahn's sleep helper for Twisted will return a Twisted Deferred (and not block the reactor): https://github.com/tavendo/AutobahnPython/blob/master/autobahn/autobahn/twisted/util.py#L29