[Python-ideas] Cofunctions PEP - Revision 4

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Aug 13 04:34:05 CEST 2010


On 13/08/10 09:39, Nick Coghlan wrote:
> On Thu, Aug 12, 2010 at 10:51 PM, Greg Ewing
> <greg.ewing at canterbury.ac.nz>  wrote:

>> There are plenty of uses for cofunctions that never send or
>> receive any values using yield
>
> Could you name some of those uses please? If you aren't getting
> answers back, they sound like ordinary iterators to me. The whole
> *point* of cofunctions to my mind is that they let you do things like
> async I/O (where you expect a result back, in the form of a return
> value or an exception) in a way that feels more like normal imperative
> programming.

I provided an example of doing exactly that during the
yield-from debate. A full discussion can be found here:

http://www.cosc.canterbury.ac.nz/greg.ewing/python/generators/yf_current/Examples/Scheduler/scheduler.txt

Are you perhaps confusing the value produced by 'yield'
with the function return value of a cofunction or a
generator used with yield-from? They're different things,
and it's the return value that gets seen by the function
doing the cocall or yield-from. That's what enables you
to think you're writing in a normal imperative style.

In the above example, for instance, I define a function
sock_readline() that waits for data to arrive on a socket,
reads it and returns it to the caller. It's used like
this:

   line = yield from sock_readline(sock)

or if you're using cofunctions,

   line = cocall sock_readline(sock)

The definition of sock_readline looks like this:

   def sock_readline(sock):
     buf = ""
     while buf[-1:] != "\n":
       block_for_reading(sock)
       yield
       data = sock.recv(1024)
       if not data:
         break
       buf += data
     if not buf:
       close_fd(sock)
     return buf

The 'yield' in there is what suspends the coroutine, and
it neither sends or receives any value. The data read from
the socket is returned to the caller by the return
statement at the end. [Clarification: block_for_reading
doesn't actually suspend, it just puts the current
coroutine on a list to be woken up when the socket is
ready.]

-- 
Greg



More information about the Python-ideas mailing list