Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python pickle: preserve trusted aliases without decoding received objects

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

pickle restores Python object graphs, including aliases, and must stay behind a trusted-data boundary.

Download Python source kit

Operation contract

An owned in-process state graph gives two receipt keys the same list. Its trusted pickle round trip retains that alias. A separate received-record function accepts a bounded UTF-8 JSON object with a declared schema. When given pickle bytes, that function rejects them without calling pickle.loads.

Failure boundary

A byte length limit does not make an untrusted pickle safe. Deserialization can invoke arbitrary object reconstruction hooks before an application can validate the returned value. JSON also needs input budgets and a schema; this small fixture checks only one bounded record and does not implement a general API parser.

Working program

python
import json
import pickle

shared_events = ["paid"]
trusted_cache = {"R-47": shared_events, "R-73": shared_events}
restored_cache = pickle.loads(pickle.dumps(trusted_cache, protocol=4))
print("alias_preserved", restored_cache["R-47"] is restored_cache["R-73"])

def parse_received_receipt(payload):
    if len(payload) > 96:
        raise ValueError("record too large")
    record = json.loads(payload.decode("utf-8"))
    if (type(record) is not dict or set(record) != {"receipt", "amount"}
            or type(record["receipt"]) is not str
            or type(record["amount"]) is not int):
        raise ValueError("wrong record shape")
    return record["receipt"], record["amount"]

print("received", parse_received_receipt(b'{"receipt":"R-47","amount":73}'))
try:
    parse_received_receipt(pickle.dumps(trusted_cache, protocol=4))
except (UnicodeError, ValueError, json.JSONDecodeError):
    print("pickle_input_rejected", True)

Output

Output
alias_preserved True
received ('R-47', 73)
pickle_input_rejected True

Costs and limits

Serialization visits the reachable object graph and allocates output bytes; restoring it allocates a new graph. The alias test is an ownership fact, not a reason to accept pickle over a network.

Common Mistakes

  • Never call pickle.loads on received or tamperable bytes.
  • A post-load type check cannot undo code already run during deserialization.
  • JSON parsing still requires a byte budget and application field checks.

Connected lessons

Test this contract.

python
pickle-trust-boundary
Storage details