这里使用持久性 ID 解决的 pickling 问题是什么?

What is the pickling problem that persistent IDs are used to solve here?

来自https://docs.python.org/3/library/pickle.html#persistence-of-external-objects

For the benefit of object persistence, the pickle module supports the notion of a reference to an object outside the pickled data stream. Such objects are referenced by a persistent ID, which should be either a string of alphanumeric characters (for protocol 0) or just an arbitrary object (for any newer protocol).

如果有人能解释一下,我将不胜感激:这里使用持久性 ID 解决的 pickling 问题是什么?换句话说,pickling不使用persistent ID会有什么问题?

具体来说,"notion of a reference to an object outside the pickled data stream"是什么意思?它是否反对其他一些概念,例如 "notion of a reference to an object inside the pickled data stream"?

“pickle 数据流”是“pickle.dumppickle.load 做什么”的通用描述。例如,数据流 是一个文件,数据可以顺序读取和读取。它是一个 pickle 数据 流,当所述流包含 pickle 产生或消耗的数据时。

Pickle 流有一个概念内部引用 - 如果同一个对象在一个流中多次出现,它只被存储一次然后被引用。但是,这仅指代已存储在流中的内容——引用不能指向流外的对象,例如原始对象。 pickle 数据流的内容在概念上是其原始数据的副本。

import pickle

bar = (1, 2)
foo = {1: 1, 2: (1, 1), 'bar': bar}

with open('foo.pkl', 'wb') as out_stream:  # open a data stream...
     pickle.dump((bar, foo), out_stream)   # ...for pickle data

with open('foo.pkl', 'rb') as in_stream:
     bar2, foo2 = pickle.load(in_stream)

assert bar2 is foo2['bar']  # internal identity is preserved
assert bar is not bar2      # external identity is broken

持久 ID 可用于指代不在流中的内容 - 例如原始对象、全局数据库句柄或另一个流中的内容,或类似内容。从概念上讲,持久 ID 仅允许其他代码处理 pickling/unpickling。然而,持久 ID 的定义和实现取决于要解决的问题。

定义和使用永久 ID 并不困难。但是,它需要一些编排和簿记。一个非常简单的示例如下所示:

import pickle

# some object to persist
# usually, one would have some store or bookkeeping in place
bar = (1, 2)


# The create/load implementation of the persistent id
# extends pickling/unpickling
class PersistentPickler(pickle.Pickler):
    def persistent_id(self, obj):
        """Return a persistent id for the `bar` object only"""
        return "it's a bar" if obj is bar else None


class PersistentUnpickler(pickle.Unpickler):
    def persistent_load(self, pers_id):
        """Return the object identified by the persistent id"""
        if pers_id == "it's a bar":
           return bar
        raise pickle.UnpicklingError("This is just an example for one persistent object!")


# we can now dump and load the persistent object
foo = {'bar': bar}
with open("foo.pkl", "wb") as out_stream:
    PersistentPickler(out_stream).dump(foo)

with open("foo.pkl", "rb") as in_stream:
    foo2 = PersistentUnpickler(in_stream).load()

assert foo2 is not foo     # regular objects are not persistent
assert foo2['bar'] is bar  # persistent object identity is preserved

作为一个real-world的例子,我的老cpy2py module使用pickle在不同的解释器之间交换数据。对于常规 value-like 对象,这意味着在一个解释器中序列化并在另一个解释器中反序列化。对于一些特殊的有状态对象,这意味着只交换一个持久 ID,该 ID 在所有连接的解释器中唯一标识该对象。

这里涉及一些簿记,但您可以将本例中的 persistent ID 视为元组 (process_id, object_id, object_type)。拥有解释器可以使用这个 ID 来查找真实对象,而其他解释器可以创建一个占位符对象。这种情况下的重点是状态没有被存储和复制,而只是被引用。