Skip to the solution
MediumDSA14 min read

What is pickling and what are its risks?

84 views

The problem

Question presented to candidate: "What does pickle do in Python, when would you use it, and why do people say you should never unpickle data you did not create yourself?"

What a strong answer should cover:

  • pickle.dumps/pickle.loads (and dump/load with binary files) turn almost any Python object graph into bytes and back, keeping types, shared references and cycles
  • Classes and functions are stored by reference (module and name), not by code, so the same class must be importable when loading; lambdas and local functions cannot be pickled
  • The risk: unpickling runs the REDUCE instruction, which calls whatever callable the stream names (via __reduce__), so pickle.loads on untrusted bytes is arbitrary code execution
  • Mitigations: do not unpickle untrusted data; sign with HMAC to detect tampering; a restricted Unpickler.find_class allowlist; prefer JSON or another data-only format across trust boundaries
  • Other limits: Python-only, not human-readable, fragile across code and version changes; protocols (default 4 on Python 3.8 to 3.13, 5 from 3.14)
  • Where it is used: multiprocessing, caching, copy-like deep clones, saving ML models (which is why loading a downloaded model file is a security decision)

Clarifying questions expected:

  • Where does the pickled data come from, and who could have modified it?
  • Does another language or a future version of the code need to read it?

Code / implementation expected: Optional β€” a round trip, and ideally a harmless __reduce__ demo of code running on load.

  • serialization
  • pickle

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWhat pickle preserves (types, shared references, cycles), protocols, and what it cannot pickle
PythonThe risk: a __reduce__ payload runs during loads; a restricted Unpickler and HMAC signing

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 113 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does a Python set find items?

Continue