[Python-ideas] make Connections iterable

Terry Reedy tjreedy at udel.edu
Mon Jan 8 15:00:32 EST 2018


On 1/8/2018 11:17 AM, Oscar Smith wrote:
> I am currently working on a program where it would be really useful if a 
> connection had a __next__ method, because then it would be much easier 
> to iterate over. It would just be an alias to recv, but would allow you 
 > to do things like merging the results of connections using heapq.merge
 > that currently are highly non-trivial to accomplish.

The reference to recv says that you must be talking about 
multiprocessing.Connection rather than sqlite3.Connection.

Since recv raises EORError when done, an alias does not work.  Try the 
following generator adaptor.

def connect_gen(connection):
     try:
         while True:
             yield connection.recv()
     except EOFError:
         pass

You could make the above the .__iter__ method of a MyConnecton subclass.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list