pickle converts Python object hierarchies into byte streams and reconstructs them later. It provides compact persistence for program state without manually writing code for each value. section 13.8
Use the module through paired dump/load operations:
- Open a binary file with 'wb' and call pickle.dump for each object to save. section 13.8
- Reopen the file with 'rb' and call pickle.load in the same order to restore the objects. section 13.8
- Pickle handles numbers, strings, lists, tuples, dictionaries, class instances, shared objects, and cyclic references. section 13.8
- Pickle cannot serialize code objects or system resources such as files and sockets. section 13.8
Save and restore related values
Store a dictionary such as {'a': 42, 'b': 3.14, 'c': 'test'} with pickle.dump inside a 'with' block, then return pickle.load from a similarly opened binary file. The restored dictionary retains its values and structure. section 13.8
import pickle
a = 42
b = 3.14
c = "test"
file = open("state", 'wb')
pickle.dump(a, file)
pickle.dump(b, file)
pickle.dump(c, file)
file.close()
Inspect the direct sequence for writing several values: import pickle, open a binary file, dump a, b, and c, then close the file. section 13.8
import pickle
file = open("state", 'rb')
a = pickle.load(file)
b = pickle.load(file)
c = pickle.load(file)
file.close()
print(f"{a=} {b=} {c=}")
a=42 b=3.14 c='test'
Inspect the matching read sequence, where pickle.load restores each value in its original order and prints 42, 3.14, and 'test'. section 13.8


