What is a cofunction and how would it work in Python?

1k Views Asked by At

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

3

There are 3 best solutions below

0
On

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).

0
On

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.

0
On

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.