← 中文资源

简体中文版本

Pickle 往返与信任边界

pickle 保留元组这类 JSON 会悄悄变宽成数组的类型(None 变 null 可完整往返);但 loads 会执行字节里内嵌的代码,信任边界是载荷是否出自你自己的系统——绝不反序列化用户或网络输入。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:settings、restored、payload。

使用要点

  • 演示输出是带标签的(json round trip :、json keeps None :、pickle round trip:),每个操作都会留下自己的一行标注。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 跨调用保留的状态放在这些顶层绑定里:settings、restored、payload。

核心语句

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

代码示例

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