7
\$\begingroup\$

The following two functions are used to compress arbitrary Python objects and send them safely via socket or email, using only printable chars. In my specific message protocol, '=' signs are also not allowed; I could have replaced them or truncate them - I chose to truncate them.

I think they work quite well speed-wise and have no unpredicted errors. I post it here for your judgement.

## Framework
import cPickle as pickle
import zlib as zl
import base64 as b64
def compress(o):
 ## First pickle
 p = pickle.dumps(o, pickle.HIGHEST_PROTOCOL)
 ## Then zip
 z = zl.compress(p, zl.Z_BEST_COMPRESSION)
 ## Then encode
 e = b64.b64encode(z)
 ## Then truncate
 t = e.rstrip("=")
 ## Then return
 return t
def decompress(s):
 ## First pad
 e = s + "=" * (-len(s) % 4)
 ## Then decode
 z = b64.b64decode(e)
 ## Then unzip
 p = zl.decompress(z)
 ## Then unpickle
 o = pickle.loads(p)
 ## Then return
 return o
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 13, 2014 at 12:49
\$\endgroup\$

1 Answer 1

11
\$\begingroup\$

Avoid single letter variable names. Spell out the words they stand for to make your code easier to read.

Your comments are useless. You are just restating the code in less detail. The only comment you should have is explaining about the '=' like you did in your post.

Don't double-space your code.

Pickle isn't safe. You can construct a pickle that does arbitrary things like delete files or what-not. So you should pretty much never be sending them over a socket.

answered Feb 13, 2014 at 16:18
\$\endgroup\$
2
  • \$\begingroup\$ pep8 says "Separate top-level function and class definitions with two blank lines."; that's why I am double-spacing my code... \$\endgroup\$ Commented Feb 13, 2014 at 18:06
  • 1
    \$\begingroup\$ I'm referring to all the newlines in your function. Not the top level space. \$\endgroup\$ Commented Feb 14, 2014 at 0:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.