[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

The "loop and a half"

On Thu, 5 Oct 2017 10:56 am, Terry Reedy wrote:

>> You're right, that construct isn't used for reading from files in
>> Python.  It _is_ commonly used for reading from things like socket
>> mysock.connect(...)
>> while True:
>>      data = mysock.recv(9999)
>>      if not data:
>>          break
>>      do_something_with(data)
>> mysock.close()
> I contend that it would be better in this case also to separate data
> access from data processing.
> Perhaps the socket module needs an update to make the boilerplate
> generator function a method, such as 'iterread'.

I was thinking the same thing as Terry.

Obviously we need the low-level socket module for those (hopefully rare) times
we need to interface with a socket at a low level. But I was thinking, why
isn't there an equivalent high-level socket interface, like for files, so we
can simply write something like:

with Socket(spam) as mysock:
    for block in mysock(blocksize):

I haven't done enough [read: any] socket programming to tell how useful and
practical this is, but it seems like an obvious enhancement.

?Cheer up,? they said, ?things could be worse.? So I cheered up, and sure
enough, things got worse.