Style question

K

Kamus of Kadizhar

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)) ?

Or something better?

-Kamus
 
P

Peter Otten

Kamus said:
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)) ?

Or something better?

remoteMD5hash = Socket.recv(256).strip()

Peter
 
P

Paul Rubin

Kamus of Kadizhar said:
remoteKD5hash = string.strip(Socket.recv(256)) ?

Or something better?

I think the preferred syntax these days is Socket.recv(256).strip()
but either way works.
 
P

Peter Hansen

Kamus said:
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.)

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top