蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python pickle:保存并恢复可信对象图

在临时文件和自建进程之间传递对象,检查共享引用、类状态及协议差异。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先确认数据来源与用途

序列化把 Python 对象图编码成 bytes,反序列化在可用的 Python 环境中恢复对象及关系。pickle 适合可控的本地快照、缓存或两个互信的 Python 进程。保存配置、训练产物或特征时要分别核对工具和版本。简单配置也可用 JSON,便于其他语言读取。

只加载你有依据确认可信的数据。反序列化可调用代码。禁止把上传、来历不明的缓存或从网络拿到的 pickle 直接交给 load 或 loads。pickletools 可查看指令但不证明载荷安全。例程只处理自己刚生成的文件和字节,进程间演示也由同一实验产生数据。

速度和体积受对象形状、协议与实现影响。接口或跨语言交换按需要选 JSON、MessagePack 等格式,并定义字段和数据类型。持久化不等于事务提交、断电恢复或多进程同步。

将对象写入文件或内存

import pickle 后,在 with 中以 wb 打开二进制文件,把对象和文件交给 dump,返回值为 None。用 rb 重开文件,load 从当前位置恢复一个对象。wb 会截断旧文件,勿用文本流代替二进制流。

dumps 直接返回 bytes,loads 接收 bytes-like 对象,包括本例的 memoryview,读出第一个对象。协议由读端自动识别。字节表示随协议和内容变化。用截断自建字节观察异常,读取到文件尾也可能得到 EOFError,不能把所有 EOFError 当作干净结尾。

对同一二进制流调用多次 dump 时,按顺序 load。实验依次读到字典、列表和整数。实际格式宜约定记录数或完整边界,便于识别缺失数据。不要用一次 loads 遍历多个拼接对象。

保持对象结构,区分活动资源与数据

整数、浮点、布尔、字符串、None 及常见容器可用。容器内仍须是可保存的对象。共享引用与循环关系可以还原,需用 is 验证身份。打开的文件、socket 和数据库连接属于活动资源,实验分别得到 TypeError。需要恢复时保存可验证的配置并重新打开资源。

可导入的顶层类和函数通常按模块及限定名保存。接收端必须有能找到的相应定义。类实例还原状态,函数体不会随 pickle 复制。lambda 和局部定义一般不可按名字恢复,实测两者可能报不同异常。类结构变更时保留版本与迁移路径。

实现 __getstate__ 与 __setstate__ 可选择保存哪些字段并恢复状态,反序列化通常不会重跑 __init__。本站示例保存版本和站点,排除临时令牌,读取时根据版本恢复默认值。跨版本时要单独验证类定义和旧状态。

实测配置、管道和计算缓存

实验先把一份普通配置写入临时二进制文件并重新读取。随后父进程把刚生成的配置字节交给自建子进程,通过管道接收可核对的 JSON。这里只传配置数据,不代表加载了真实模型或证明其可移植。

缓存以算法版本和输入共同作键。对 6 首次计算,第二次命中。换成 3 产生另一条结果,再输入 6 仍命中。核对实际调用次数。多进程共享缓存还需原子写入、并发控制和失效策略。

显式选择协议并核对接收条件

当前实测 CPython 3.12 的默认协议为 4,最高为 5。3.0 到 3.7 默认 3,3.8 到 3.13 默认 4,3.14 起官方文档列为 5。HIGHEST_PROTOCOL 会随解释器演进,负的 protocol 参数同样选择可用最高值。对外交换时应按接收端明确固定协议。

协议 0 便于查看但仍是 bytes,带有非 ASCII 的字符串时不能假定所有字节都是 ASCII。协议 1 为早期二进制格式,2 提升新式类支持,3 专门支持 bytes,4 加入帧及其他改进。协议 5 可把支持缓冲区协议的数据分开传送。示例检查帧、指令、带外缓冲区及缺失缓冲区的异常。

下载本站 ZIP,解压后运行 python python-pickle.py。实验用当前 Python 验证 0 到 5 的行为,不代表老版本解释器或真实模型文件已兼容。

下载本站 pickle 实验 ZIP

所需环境:CPython 3.12 标准库

ZIP SHA256:e61b1b0364d414fe7e98de08e13712fb9ed5ca795845bbcf7b08e6d392e05a54

可保存的数据

类型、接口或协议作用和条件
int / float / bool / str分别恢复值及类型,布尔值与整数单独观察。
list / tuple / dict / set保持容器类型,成员也要可序列化。
None可作为值保存,读回 None。
自定义类实例保存状态,接收端须找到与保存时对应的类名与模块。
嵌套结构支持可序列化成员构成的对象图,可还原共享和自引用。

读写接口与协议常量

类型、接口或协议作用和条件
pickle.dump(obj, file, protocol=None)向二进制文件对象写一个对象,返回 None。用 with 管理文件。
pickle.load(file)从二进制流当前位置读一个对象,自动识别协议。无下一个对象时可能出现 EOFError。
pickle.dumps(obj, protocol=None)返回 bytes,无需文件对象。
pickle.loads(data)从 bytes-like 输入恢复第一个对象。只能加载可信数据。
pickle.HIGHEST_PROTOCOL可用协议上限,供显式选用。接收端须支持该版本。
pickle.DEFAULT_PROTOCOL当前解释器省略协议时的默认值。3.12 为 4,3.14 起为 5。

六种历史协议

类型、接口或协议作用和条件
0历史上便于阅读的协议。输出仍是字节流,不能保证全为 ASCII。
1早期二进制格式。实验可见二进制备忘录写入指令。
2Python 2.3 引入,改进了新式类的保存。
3Python 3.0 引入并支持 bytes,Python 2 无法读取。默认协议沿用到 3.7。
4Python 3.4 引入,包括帧、大对象和更多对象类型支持。默认于 3.8 到 3.13。
5Python 3.8 引入带外缓冲区并改善带内传输性能。可另行传送并提供所需缓冲区。

本章自编源码与运行范围

Python · 阅读源码
"""Round-trip only data created by this example. Never load outside pickle data."""

import io
import json
import pickle
import pickletools
import socket
import sqlite3
import subprocess
import sys
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory


class Sensor:
    def __init__(self, station, samples):
        self.station = station
        self.samples = samples


class Snapshot:
    def __init__(self, station, temporary_token):
        self.station = station
        self.temporary_token = temporary_token
        self.restore_path = "init"

    def __getstate__(self):
        return {"schema": 2, "station": self.station}

    def __setstate__(self, state):
        if state["schema"] != 2:
            raise ValueError("unsupported snapshot schema")
        self.station = state["station"]
        self.temporary_token = None
        self.restore_path = "setstate"


def calibration(value):
    return value + 2


unnamed_calibration = lambda value: value + 2


def observe():
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, actual=actual, expected=expected, input=inputs,
                           operation=operation, passed=True))

    def rejects(name, expected, inputs, operation, call):
        try:
            call()
        except expected as error:
            check(name, type(error).__name__, expected.__name__, inputs, operation)
        else:
            raise AssertionError(name)

    def opcodes(data):
        return [(code.name, arg) for code, arg, _ in pickletools.genops(data)]

    data = {"station": "东港", "bands": [3, 7, 11], "active": True}
    with TemporaryDirectory(prefix="mbsky-pickle-") as directory:
        work = Path(directory)
        record = work / "station.pkl"
        with record.open("wb") as stream:
            result = pickle.dump(data, stream, protocol=4)
        check("binary dump returns None and writes bytes",
              [result, record.read_bytes()[:2].hex()], [None, "8004"], data, "Write to wb and read the header bytes")
        with record.open("rb") as stream:
            restored = pickle.load(stream)
        check("binary load restores nested record", restored, data, data, "Open the owned file as rb and load one object")

        sequence = [{"count": 4}, ["晨间", "晚间"], 29]
        with record.open("wb") as stream:
            for value in sequence:
                pickle.dump(value, stream, protocol=4)
        with record.open("rb") as stream:
            actual = [pickle.load(stream) for _ in sequence]
            check("multiple file objects preserve order", actual, sequence, sequence, "Read three dump records in order")
            rejects("EOF after final object", EOFError, "same stream after record three", "Try one extra load",
                    lambda: pickle.load(stream))

        config = {"kind": "threshold", "limit": 18, "labels": ["船位", "风向"]}
        config_file = work / "config.pkl"
        with config_file.open("wb") as stream:
            pickle.dump(config, stream, protocol=4)
        with config_file.open("rb") as stream:
            check("configuration round trip", pickle.load(stream), config, config, "Save and reload configuration fields")
        check("plain config also fits JSON", json.loads(json.dumps(config)), config, config,
              "Round-trip the same simple configuration through JSON")
        payload = pickle.dumps(config, protocol=4)
        child = subprocess.run([sys.executable, "-I", "-B", "-X", "utf8", "-c",
            "import json,pickle,sys;print(json.dumps(pickle.load(sys.stdin.buffer)))"],
            input=payload, capture_output=True, timeout=10, check=True)
        check("owned process pipe transfers bytes", [json.loads(child.stdout), child.stderr.decode("utf-8")],
              [config, ""], config, "Send only the parent's just-generated data to an owned child on stdin")

        cache_file = work / "cache.pkl"
        calls = []

        def square_total(n):
            key = ("squares-v1", n)
            values = {}
            if cache_file.exists():
                with cache_file.open("rb") as stream:
                    values = pickle.load(stream)
            if key not in values:
                calls.append(n)
                values[key] = sum(index * index for index in range(n))
                with cache_file.open("wb") as stream:
                    pickle.dump(values, stream, protocol=4)
            return values[key]

        actual = [square_total(6), square_total(6), square_total(3), square_total(6)]
        check("cache miss hit and second key", [actual, calls], [[55, 55, 5, 55], [6, 3]],
              [6, 6, 3, 6], "Read cache on repeat, compute only on misses and keep earlier entries")
        with record.open("rb") as stream:
            rejects("open file cannot be pickled", TypeError, "open binary file", "Try to serialize the open handle",
                    lambda: pickle.dumps(stream))
    with socket.socket() as sock:
        rejects("socket cannot be pickled", TypeError, "unused local socket", "Serialize a handle without connecting",
                lambda: pickle.dumps(sock))
    with closing(sqlite3.connect(":memory:")) as db:
        rejects("database connection cannot be pickled", TypeError, "in-memory SQLite connection", "Try to serialize the connection",
                lambda: pickle.dumps(db))

    objects = [8, 2.5, False, "东港", [4], (5,), {"gust": 9}, {2, 6}, None]
    restored = pickle.loads(pickle.dumps(objects, protocol=4))
    check("mixed types and nested values", [restored == objects, [type(value).__name__ for value in restored]],
          [True, ["int", "float", "bool", "str", "list", "tuple", "dict", "set", "NoneType"]],
          "nine distinct values within one list", "Compare values and actual types after a round trip")
    shared = ["标记"]
    graph = [shared, shared]
    graph.append(graph)
    restored = pickle.loads(pickle.dumps(graph, protocol=4))
    check("object graph retains aliases and cycle", [restored[0] is restored[1], restored[2] is restored],
          [True, True], "one reused child and one self-edge", "Compare restored identities")
    reading = Sensor("西港", [9, 12])
    result = pickle.loads(pickle.dumps(reading, protocol=4))
    check("top-level class instance state", [type(result) is Sensor, result.station, result.samples],
          [True, "西港", [9, 12]], "Sensor with two attributes", "Restore the instance using the available class")
    data = pickle.dumps(calibration, protocol=4)
    check("top-level function restored by name", [pickle.loads(data) is calibration, pickle.loads(data)(7)],
          [True, 9], "function at module scope", "Restore the reference and call the available function")
    rejects("lambda does not have importable name", pickle.PicklingError, "module-level lambda",
            "Try to pickle the lambda by qualified name", lambda: pickle.dumps(unnamed_calibration))
    rejects("local function lookup fails", AttributeError, "function created in local scope",
            "Try to pickle the local function without calling it", lambda: pickle.dumps(lambda: 1))
    snap = pickle.loads(pickle.dumps(Snapshot("渡口", "temporary"), protocol=4))
    check("custom state excludes temporary value and restores via hook", [snap.station, snap.temporary_token, snap.restore_path],
          ["渡口", None, "setstate"], "Snapshot with a transient value", "Round-trip only versioned state through both hooks")

    binary = pickle.dumps([2, 4, 8], protocol=4)
    check("dumps bytes and loads memoryview", [type(binary).__name__, pickle.loads(memoryview(binary))],
          ["bytes", [2, 4, 8]], [2, 4, 8], "Serialize to memory and decode a bytes-like view")
    check("loads reads one object before trailing record", pickle.loads(binary + pickle.dumps(99, protocol=4)),
          [2, 4, 8], "two concatenated, self-generated records", "Use loads once on both byte sequences")
    rejects("text stream is not binary", TypeError, "io.StringIO()", "Try dump against a stream that expects str",
            lambda: pickle.dump([], io.StringIO()))
    rejects("truncated own frame raises", pickle.UnpicklingError, "last byte removed from own protocol 4 list",
            "Load the truncated local fixture", lambda: pickle.loads(binary[:-1]))
    for protocol, value, opcode in [(0, "é", "UNICODE"), (1, [9], "BINPUT"), (2, reading, "NEWOBJ"),
                                    (3, b"\x00", "SHORT_BINBYTES"), (4, [2, 4, 8], "FRAME")]:
        encoded = pickle.dumps(value, protocol=protocol)
        restored = pickle.loads(encoded)
        equal = vars(restored) == vars(value) if protocol == 2 else restored == value
        check("protocol " + str(protocol) + " round trip and opcode", [equal, opcode in [name for name, arg in opcodes(encoded)]],
              [True, True], {"protocol": protocol, "input_type": type(value).__name__}, "Load and inspect the real protocol operations")
    text_pickle = pickle.dumps("é", protocol=0)
    check("protocol zero is still a byte stream", [type(text_pickle).__name__, text_pickle.isascii(), pickle.loads(text_pickle)],
          ["bytes", False, "é"], "é", "Compare the historical text-oriented format against the ASCII predicate")

    actual_default = opcodes(pickle.dumps([7]))[0][1]
    expected_default = 5 if sys.version_info >= (3, 14) else 4
    check("default protocol matches current CPython", [actual_default, pickle.DEFAULT_PROTOCOL],
          [expected_default, expected_default], [7], "Inspect header selected when protocol is omitted")
    check("highest protocol and negative selection", [opcodes(pickle.dumps([7], protocol=-1))[0][1],
          opcodes(pickle.dumps([7], protocol=pickle.HIGHEST_PROTOCOL))[0][1]],
          [pickle.HIGHEST_PROTOCOL] * 2, [7], "Compare explicit highest and negative protocol selection")
    value = bytearray(b"sea")
    buffers = []
    encoded = pickle.dumps(pickle.PickleBuffer(value), protocol=5, buffer_callback=buffers.append)
    loaded = pickle.loads(encoded, buffers=buffers)
    check("protocol five transfers an out-of-band buffer", [len(buffers), memoryview(loaded).tobytes().hex(),
          "NEXT_BUFFER" in [name for name, arg in opcodes(encoded)]],
          [1, "736561", True], "one three-byte buffer", "Keep the buffer separate and supply it while restoring")
    value[0] = ord("t")
    check("supplied mutable buffer remains shared", memoryview(loaded).tobytes().hex(), "746561",
          "update first byte of original bytearray", "Read the restored buffer view after the update")
    rejects("protocol five without buffers raises", pickle.UnpicklingError, "same out-of-band pickle with no buffers",
            "Restore without the required companion buffer", lambda: pickle.loads(encoded))
    return checks


if __name__ == "__main__":
    print(json.dumps(observe(), ensure_ascii=True, indent=2))
运行本章核心实例

所需环境:Owned-only binary file, IPC, object identity and pickle protocol observations

当前源码 SHA256:6f2f33b8abc49a183cb1ad5e3254ab951f88a9142c21f690e0649a19bf4c1a64

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据