1 min read

Python Pickle Module

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. "Pickling" is the process whereby a Python object hierarchy is converted into a byte stream, and "unpickling" is the inverse operation.

Importing the Module

import pickle

Pickling (Serialization)

To serialize an object hierarchy, you simply use pickle.dump().

import pickle

data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}

with open('data.pickle', 'wb') as f:
    pickle.dump(data, f)

Unpickling (Deserialization)

To deserialize a data stream, you use pickle.load().

import pickle

with open('data.pickle', 'rb') as f:
    data = pickle.load(f)
    print(data)

Pickling to/from Strings

  • pickle.dumps(): Returns the pickled representation of the object as a bytes object.
  • pickle.loads(): Reads a pickled object hierarchy from a bytes object.
import pickle

data = [1, 2, 3]
serialized = pickle.dumps(data)
print(serialized)

deserialized = pickle.loads(serialized)
print(deserialized)

Security Warning

Warning: The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never unpickle data received from an untrusted or unauthenticated source.

programming/python/python