all Python 3pickleterm
pickle.Pickler
serialization
A class that writes objects to a binary file in pickle format; dump(obj) writes the next object. It lets you customise serialization.
Syntax
p = pickle.Pickler(file, protocol=None, *, fix_imports=True, buffer_callback=None)
pickle.dump() is a one-off Pickler(file).dump(obj). Your own Pickler is for writing many objects to one stream or overriding persistent_id, reducer_override and dispatch_table. The trap: a Pickler remembers objects it has written, so if you mutate a list after dump() and write it with the same Pickler again, only a reference to the earlier copy goes out — the change is lost; call clear_memo() between writes. Read it back with Unpickler, and only from a trusted source.
Examples
import io, pickle
buf = io.BytesIO()
p = pickle.Pickler(buf)
items = [1, 2]
p.dump(items)
items.append(3)
p.dump(items)
buf.seek(0)
u = pickle.Unpickler(buf)
print(u.load(), u.load()) # → [1, 2] [1, 2]
import io, pickle
buf = io.BytesIO()
p = pickle.Pickler(buf)
items = [1, 2]
p.dump(items)
items.append(3)
p.clear_memo()
p.dump(items)
buf.seek(0)
u = pickle.Unpickler(buf)
print(u.load(), u.load()) # → [1, 2] [1, 2, 3]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy