all Python 3picklefunction
pickle.dumps()
serialization
Turns an object into bytes in pickle format — for passing between processes, caching or storing in a database.
Syntax
data = pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)
It returns bytes, not str: they cannot go into a text field or JSON without base64. The bytes depend on the protocol, the version and even key insertion order, so comparing dumps(a) == dumps(b) instead of a == b is wrong — equal dicts give different bytes. Lambdas, generators, open files, connections and locks cannot be pickled. The reverse, loads(), runs code from the data — accept such bytes only from yourself.
Examples
import pickle
print(type(pickle.dumps({'a': 1})).__name__) # → bytes
print(pickle.dumps({'a': 1, 'b': 2}) == pickle.dumps({'b': 2, 'a': 1})) # → False
try:
pickle.dumps(lambda x: x)
except pickle.PicklingError:
print('лямбду не сохранить') # → лямбду не сохранить
See also
Open in the full glossarydocs.python.orgReport an inaccuracy