bpo-2628: support BLOCK mode for retrbinary by knoxvague · Pull Request #29337 · python/cpython (original) (raw)

Adding (+) chunks of bytes on every iteration is not very efficient. You could use a bytearray instead. Not tested:

    buff = bytearray()
    curr_length = blocklength
    while len(buff) < blocklength:
        chunk = conn.recv(curr_length)
        buff.extend(chunk)
        curr_length -= len(chunk)
    data = bytes(buff)

In order to avoid making this method too complex, perhaps it makes sense to encapsulate this logic in a utility function (again, not tested):

def _read_until(sock, length): if length <= 0: return b"" buff = bytearray() curr_length = length while len(buff) < length: chunk = sock.recv(curr_length) buff.extend(chunk) curr_length -= len(chunk) return bytes(buff)