[Python-ideas] make Connections iterable

Chris Angelico rosuav at gmail.com
Tue Jan 9 11:27:04 EST 2018

On Tue, Jan 9, 2018 at 11:12 PM, Random832 <random832 at fastmail.com> wrote:
> On Tue, Jan 9, 2018, at 05:46, Nick Coghlan wrote:
>> If you view them as comparable to subprocess pipes, then it can be
>> surprising that they're not iterable when using a line-oriented
>> protocol.
>> If you instead view them as comparable to socket connections, then the
>> lack of iteration support seems equally reasonable.
> Sockets are files - there's no fundamental reason a stream socket using a line-oriented protocol (which is a common enough case), or a datagram socket, shouldn't be iterable. Why aren't they? Making sockets iterable would be a separate discussion, but I don't think this is necessarily an argument.

Only in POSIX. On other platforms, sockets are most definitely NOT
files. And datagram sockets don't really make sense to iterate over.

Part of the problem with even POSIX stream sockets (either TCP or Unix
domain) is what you do when there's nothing to read. Do you block,
waiting for a line? Do you raise StopIteration and then subsequently
become un-finished again (which, according to Python semantics, is a
broken iterator)? Do you yield a special value that says "no data yet
but more maybe later"?? Blocking is the only one that makes sense, and
that only if you run two threads, one for reading and one for writing.
(Unless you're using a unidirectional socket, basically a TCP-enabled
or filesystem-named pipe. Far from common.)


More information about the Python-ideas mailing list