Keep pickle and shelve within Trusted Boundaries
Core idea
pickle serializes Python object graphs to bytes and can preserve relationships not represented by JSON. Unpickling can execute code: never load data from an untrusted or unauthenticated source. shelve stores values using pickle behind a dictionary-like persistent interface, so the same trust boundary applies.
import pickleoriginal = ("bin", {1, 2})# Only bytes generated within this example.payload = pickle.dumps(original)restored = pickle.loads(payload)print(type(restored).__name__, restored == original)The trusted local round-trip preserves tuple and set types. No external pickle is loaded.
Persist a local shelf value
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import shelve with shelve.open(str(root / "state")) as db: db["counts"] = [2, 4] counts = db["counts"] counts.append(6) db["counts"] = counts print(db["counts"])Assign the changed list back; default writeback=False does not track arbitrary in-place modifications. The temporary root owns the backing files.
Common mistake
Do not accept pickle or shelf files from external users. A filename, checksum without trusted authentication, or try/except does not make deserialization safe. Shelve storage details and concurrent access support vary by backend; do not use it as a multiwriter database.
Practice
Explain why an externally uploaded pickle should be rejected, then round-trip a tuple created inside your own process.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trusted object persistence
Check your understanding of pickle and shelve.
What is printed?
import picklex=(1,2)print(type(pickle.loads(pickle.dumps(x))).__name__)What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import shelve with shelve.open(str(root/"db")) as db: db["x"]=[1] copy=db["x"] copy.append(2) print(db["x"])Which input is suitable for the pickle example?
Why does shelve share pickle’s trust restriction?