Skip to main content
Albero Academy

Pickle

Serialise arbitrary Python objects to bytes — and why you must never unpickle untrusted data.

File Handling8 min

Pickle serialises almost any Python object — custom classes, nested structures, trained models — to bytes, so you can save program state to disk and restore it later. Where JSON only handles basic types, pickle handles the whole object graph.

Saving & restoring objects

Pickle works in binary mode ("wb"/"rb") since it writes bytes, not text:

pickle
import pickle
model = {"weights": [0.1, 0.5], "trained": True}
with open("model.pkl", "wb") as f: # binary write
pickle.dump(model, f)
with open("model.pkl", "rb") as f: # binary read
restored = pickle.load(f) # a full, identical object

The security warning

Pickle vs JSON

PickleJSON
HandlesAny Python objectBasic types only
FormatPython-only bytesUniversal text
SafetyUnsafe on untrusted dataSafe to parse
Use forYour own local stateSharing/interchange

Key takeaways

  1. 01pickle serialises arbitrary Python objects (not just basic types) to bytes.
  2. 02Use binary modes ("wb"/"rb").
  3. 03Never unpickle untrusted data — it can execute arbitrary code.
  4. 04Use pickle for your own local state; use JSON for interchange with other systems.

Finished this chapter?

Mark it complete to track your progress through Python.