为什么这个 python 高速公路代码需要使用 'yield' 关键字?

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

为什么这个 python 高速公路示例代码使用 yield sleep(1) 而不是简单的 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)

使用yield sleep(1)可以return一个结果并做其他事情。

但是简单地使用 sleep(1) 将导致 main 始终在函数 onJoin 中。 这是一个死循环。

点击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.

因为 Python 的标准库 sleep 将阻塞 Twisted 反应器,而 Autobahn 的 sleep Twisted 助手将 return 一个 Twisted Deferred(而不是阻塞反应堆):https://github.com/tavendo/AutobahnPython/blob/master/autobahn/autobahn/twisted/util.py#L29