蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHONOwned-only binary file, IPC, object identity and pickle protocol observationspython-pickle.py
python-pickle.py202 行
"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/python-lab/python-pickle.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-pickle.py,或下载右侧课程工程包。
  2. 确认本地已准备 Owned-only binary file, IPC, object identity and pickle protocol observations。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a296.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习