Pickle Round Trip And Trust Boundary

pickle round trips tuples that JSON silently widens to lists while None survives as null; loads must only ever receive payloads your own system produced.

PythonSecurity Boundaries

Code

pythonsnippet
20 lines
import json
import pickle

# JSON handles dicts of primitives but silently widens Python types:
# tuples become lists, while pickle preserves the exact shape
settings = {'window': (800, 600), 'opened': None}
print('json round trip  :', json.loads(json.dumps(settings))['window'])
print('json keeps None  :', json.loads(json.dumps(settings))['opened'])

restored = pickle.loads(pickle.dumps(settings))
print('pickle round trip:', type(restored['window']).__name__, restored['window'])

# protocol=5 (PEP 574) is the highest protocol; plain containers
# round trip the same under any protocol version
payload = pickle.dumps(settings, protocol=pickle.HIGHEST_PROTOCOL)
print('payload bytes    :', len(payload))

# pickle.loads executes code embedded in the bytes — the trust boundary
# is whether your own system produced the payload: never load user or
# network input, prefer JSON or a signed format for untrusted sources

How it works

All the work happens on the top-level bindings: settings, restored, payload.

Caveats

  • Nothing sits in the dependency list; the runtime itself supplies it all.

Applying it

Look for the json round trip :, json keeps None :, pickle round trip: prefixes once the file starts running; each one ties a printed line to the step that produced it.

Statements that decide the outcome

settings = {'window': (800, 600), 'opened': None}

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `settings`, `restored`, `payload`.