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