为什么不能将 Deferred 传递给 Python Twisted 中的回调?

发布于 2024-08-23 09:26:29 字数 218 浏览 11 评论 0原文

d = Deferred()
d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed

这是为什么呢?我查看了代码并提交消息/Trac,没有发现为什么会出现这种情况。绕过这个问题的最明显的方法是将 Deferred 放入一个元组中,但为什么首先会出现此限制呢?

d = Deferred()
d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed

Why is this? I looked through the code and commit messages / Trac and see no reason why this should be the case. The most obvious way to bypass this is to put the Deferred in a tuple, but why is this restriction here in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花心好男孩 2024-08-30 09:26:29

这有两个相关的原因。

首先,它有助于尽早发现可能发生的错误 - 在发生错误的地方附近。 Deferred 会被回调,结果会被传递给它的所有回调。如果您将结果本身设置为 Deferred,那么这些回调在被调用时就无能为力。这引出了下一个原因。

其次,Deferred 支持链接,它处理传递 Deferred 时可能遇到的最常见用例。给定两个 Deferred,a 和 b,链接会导致 a 暂停处理自己的回调链,直到 b 得到结果,然后 a 使用 b 的结果恢复其回调链。这就是当 Deferred 上的回调返回 Deferred 时会发生的情况。也可以使用 Deferred.chainDeferred 显式完成。

There are two related reasons for this.

First, it helps catch what is likely a mistake early - near the place where the mistake is being made. A Deferred is called back with a result which is then passed to all of its callbacks. If you make the result itself a Deferred, then there's not much these callbacks can do when they're called. This leads me to the next reason.

Second, Deferreds support be chaining which handles the most common use cases one might have for passing in a Deferred. Given two Deferreds, a and b, chaining causes a to pause processing its own callback chain until b has a result, then a resumes its callback chain with the result of b. This is what happens when a callback on a Deferred returns a Deferred. It can also be done explicitly with Deferred.chainDeferred.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文