什么是余函数以及它在 Python 中如何工作?

发布于 2024-10-19 19:33:07 字数 119 浏览 2 评论 0 原文

我正在阅读 PEP-3153,但我不明白问题是什么是它想要解决的。 您能解释一下吗?

I am reading PEP-3153, but I don't understand what the problem is it wants to address.
Could you please explain?

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

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

发布评论

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

评论(3

栀梦 2024-10-26 19:33:07

你可以谷歌“Python协程”并获得很多有用的信息。 这是一个演示文稿 (PDF) 我前段时间遇到过,对我来说似乎不错关于如何和为什么。 源代码也可用(其中包括 PDF,所以如果您想要两者,只需下载这个)。此演示文稿的主页包含指向各个源文件的链接。

You can Google "Python coroutines" and get a lot of good information. Here is a presentation (PDF) I ran across some time ago that seemed pretty good to me about the how and why. The source code is also available (this includes the PDF, so if you want both, just download this). The home page for this presentation has links to the individual source files.

绝不服输 2024-10-26 19:33:07

你知道什么是发电机吗?一种可以停止处理的函数,以便在恢复生成下一个值之前可以返回(“产生”)一个值。

好吧,协程(尽管 PEP 使用术语“cofunction”)与此类似,只是它不需要生成任何内容,并且可以转移到另一个协程(PEP 语言中的“cocall”) 。此功能有各种各样的用途,例如能够在此基础上构建本质上是您自己的轻量级协作线程实用程序(我也看到过一些非常简洁的模板库以这种方式完成),尽管当您可以时这特别有用也可以在协程调用的函数之间进行传输。

请注意,没有任何东西需要协程。您始终可以用不同的方式编写代码并且无需它们。只是有时这样做要复杂得多(由于需要更明确的状态管理)。

You know what a generator is? A function that can stop its processing so that it can return (“yield”) a value before being resumed to produce the next one.

Well, a coroutine (though the PEP uses the term “cofunction”) is like that except that it doesn't ever need to yield anything, and it can instead transfer into another coroutine (a “cocall” in the language of the PEP). There's all sorts of uses of this capability, such as being able to construct what is essentially your own lightweight cooperative threading utility on top of this (I've seen some pretty neat templating libraries done this way too) though that's particularly useful when you can transfer between functions called from coroutines too.

Note that there is nothing that requires coroutines. You can always write the code in a different way and do without them. It's just sometimes much more complicated to do so (due to the need for more explicit state management).

﹏半生如梦愿梦如真 2024-10-26 19:33:07

cofunctions 提案只是对 python 现有协程设施的清理,据了解,这些设施是基于生成器的(有点链接到 动机:发出错误消息更明确的是,避免了通过是否存在yield关键字来确定函数是否是生成器的混乱,并且更容易在协程之间进行委托。

The cofunctions proposal is just a clean-up of python's existing coroutine facilities, which up to know were based on generators (kindall linked to the canonical presentation). The PEP does explain the motivations: making error messages more explicit, avoiding the kludge of determining if a function is a generator by the presence of the yield keyword, and making it easier to delegate between coroutines.

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