klenwell information services : PythonPickles

Python Pickles

return to DevPython

Serializing and unserializing objects with pickles.

Pickle

Serialize / Unserialize as a String

# simple example
>>> import pickle
>>> l = [1,2,3,4]
>>> p = pickle.dumps(l)
>>> p
'(lp0\nI1\naI2\naI3\naI4\na.'
>>> r = pickle.loads(p)
>>> r
[1, 2, 3, 4]

# with HIGHEST PROTOCOL
>>> p = pickle.dumps(s, pickle.HIGHEST_PROTOCOL)
>>> p
'\x80\x02]q\x00(K\x01K\x02K\x03K\x04e.'
>>> r = pickle.loads(l)
>>> r
[1, 2, 3, 4]

# code example
import pickle
l = [1, 2, 3, 4]
p = pickle.dumps(l, pickle.HIGHEST_PROTOCOL)
r = pickle.loads(p)
assert r == l



References

http://docs.python.org/library/pickle.html