在Twisted有一些 api 可以返回 Deferred
.有没有一种快速的方法来测试返回值是 Deferred
还是实际上是返回值。
我觉得一直这样做看起来很草率。
stop_listening_result = self.listening_port.stopListening()
if isinstance(stop_listening_result, defer.Deferred):
stop_listening_result.addCallback(self.start)
else:
self.start()
此特定示例在 IListeningPort
上调用 stop
,从他们的文档中说:
`停止监听此端口。
如果它没有立即完成,将返回在完成时触发的 Deferred。
最佳答案
听起来你想要maybeDeferred
.它将同步结果包装在已经完成的 Deferred
中。正如文档所述:
Invoke a function that may or may not return a Deferred.
Call the given function with the given arguments. If the returned object is a Deferred, return it. If the returned object is a Failure, wrap it with fail and return it. Otherwise, wrap it in succeed and return it. If an exception is raised, convert it to a Failure, wrap it in fail, and then return it.
那么你总是可以假设一个 Deferred
已经返回:
from twisted.internet.defer import maybeDeferred
stop_listening_result = maybeDeferred(self.listening_port.stopListening)
stop_listening_result.addCallback(self.start)
关于python - 检查扭曲的返回值是否为 Deferred,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045354/