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:
import picklemodel = {"weights": [0.1, 0.5], "trained": True}with open("model.pkl", "wb") as f: # binary writepickle.dump(model, f)with open("model.pkl", "rb") as f: # binary readrestored = pickle.load(f) # a full, identical object
The security warning
Pickle vs JSON
| Pickle | JSON | |
|---|---|---|
| Handles | Any Python object | Basic types only |
| Format | Python-only bytes | Universal text |
| Safety | Unsafe on untrusted data | Safe to parse |
| Use for | Your own local state | Sharing/interchange |
Key takeaways
- 01pickle serialises arbitrary Python objects (not just basic types) to bytes.
- 02Use binary modes ("wb"/"rb").
- 03Never unpickle untrusted data — it can execute arbitrary code.
- 04Use pickle for your own local state; use JSON for interchange with other systems.
