Style question

Peter Hansen peter at
Mon Dec 15 15:29:37 CET 2003

Kamus of Kadizhar wrote:
> I have the following line:
> remoteMD5hash = Socket.recv(256)
> But what I really want is remoteMD5hash.strip()
> What's the best way to say that on one line?
> remoteKD5hash = string.strip(Socket.recv(256)) ?

Given that a socket.recv() call makes no guarantees about how
many bytes of data it returns, other than being somewhere between
one byte (if the socket is still open) and 256 bytes, neither the
suggested alternatives nor the above approach are "better style"
since both are potentially quite buggy.

Instead, you need to separate the two things you are doing.
One is receiving data from a TCP (?) socket, which requires
more logic than just .recv(256).  The other thing is massaging
your data, in this case a simple strip operation.

Therefore your code should look something more like this:

def receiveAllDataFromSocket(sock):
    # insert fancy logic here... check the archives or examples
    # on, say, the Python Cookbook site to learn how

def cleanMd5Hash(data):
    return data.strip()

# logic in your own code
data = receiveAllDataFromSocket(sock)
remoteKD5hash = cleanMd5Hash(data)

...or something like that.

(Okay, I'm probably going overboard on the second part, since nobody 
really needs to encapsulate a strip() call in a subroutine, but you
for sure aren't safe just doing one .recv() on a socket, and in any
case mixing the two operations -- receiving data and massaging it --
is not good style in any case.)


More information about the Python-list mailing list