简体   繁体   中英

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 simply sleep(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)

因为Python的标准库sleep将阻止Twisted反应器,而Autobahn的Twisted sleep帮助程序将返回Twisted Deferred(而不是阻止反应器): https : //github.com/tavendo/AutobahnPython/blob/master/autobahn/autobahn/扭曲/ util.py#L29

Using yield sleep(1) can return a result and do other things.

But using simply sleep(1) will cause main always in function onJoin . It's a deadless loop.

Click here

The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator's methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to generator's caller. By suspended we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression was just another external call. The value of the yield expression after resuming depends on the method which resumed the execution.

All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where should the execution continue after it yields; the control is always transferred to the generator's caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM