[Python-ideas] Cofunctions: It's alive! Its alive!
greg.ewing at canterbury.ac.nz
Sun Aug 8 04:00:49 CEST 2010
Carl M. Johnson wrote:
> It seems like the main use case that comes to mind for
> cofunctions is, essentially, quick and dirty cooperative multitasking.
> Of course, as we all know on the OS side of things, cooperative
> multitasking has been more or less phased out ...
> in favor of preemptive multitasking.
They're meant for different things. Preemptive multitasking
is for concurrency -- you have N cores and they can all
physically run at the same time. Cooperative multitasking
is a program structuring technique, for when it helps to
think in terms of several separate state machines interacting
with each other.
The existence of widely-used frameworks such as Twisted
attests that there are very real use cases for non-preemptive
Recently I've come across a discrete-event simulation package
called SimPy that does process-oriented simulation using
the generator/trampoline technique. This seems like an ideal
use case for cofunctions, and I'm going to look into creating
a cofunction-based version of it.
> Hmm. I think this can be pushed even farther. ...
> Then when, for example, you accidentally try to
> send a string to sum, you could be told at compile time "TypeError." I
> propose we call this "Static TypeErroring". ;-)
Well, I think you're indulging in extrapolation ad absurdum
My initial proposal for cofunctions was considerably more
dynamic, but it got criticised for not being explicit enough.
It also wasn't capable of detecting and clearly diagnosing
all of the errors that the current one can.
> OTOH, "Explicit is better than implicit." So, maybe the explicit
> syntax for cocalling is worth the pain.
When you consider that the alternative to writing 'cocall'
in certain places is to write 'yield from' or some equivalent
thing in all the same places, I'd say the cofunction way is
actually *less* painful.
"Doctor, it hurts when I do this."
"Don't do that, then."
"But if I don't, it hurts twice as badly!"
More information about the Python-ideas