cPickle - 酸洗同一个对象的不同结果 [英] cPickle - different results pickling the same object

查看:46
本文介绍了cPickle - 酸洗同一个对象的不同结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人能够解释此代码片段?

Is anyone able to explain the comment under testLookups() in this code snippet?

我已经运行了代码,并且评论所说的确实是真的.但是我想了解为什么它是正确的,即为什么 cPickle 会根据引用方式为同一对象输出不同的值.

I've run the code and indeed what the comment sais is true. However I'd like to understand why it's true, i.e. why is cPickle outputting different values for the same object depending on how it is referenced.

和引用计数有关系吗?如果是这样,那是不是某种错误 - 即腌制和反序列化的对象将具有异常高的引用计数,并且实际上永远不会被垃圾收集?

Does it have anything to do with reference count? If so, isn't that some kind of a bug - i.e. the pickled and deserialized object would have an abnormally high reference count and in effect would never get garbage collected?

推荐答案

它正在查看引用计数,来自 cPickle 源:

It is looking at the reference counts, from the cPickle source:

if (Py_REFCNT(args) > 1) {
    if (!( py_ob_id = PyLong_FromVoidPtr(args)))
        goto finally;

    if (PyDict_GetItem(self->memo, py_ob_id)) {
        if (get(self, py_ob_id) < 0)
            goto finally;

        res = 0;
        goto finally;
    }
}

pickle 协议必须处理对同一个对象的多个引用.为了防止在 depickled 时复制对象,它使用备忘录.备忘录基本上将索引映射到各种对象.pickle 中的 PUT (p) 操作码将当前对象存储在此备忘录字典中.

The pickle protocol has to deal with pickling multiple references to the same object. In order to prevent duplicating the object when depickled it uses a memo. The memo basically maps indexes to the various objects. The PUT (p) opcode in the pickle stores the current object in this memo dictionary.

但是,如果对象只有一个引用,则没有理由将其存储在备忘录中,因为不可能需要再次引用它,因为它只有一个引用.因此,此时 cPickle 代码会检查引用计数以进行一些优化.

However, if there is only a single reference to an object, there is no reason to store it it the memo because it is impossible to need to reference it again because it only has one reference. Thus the cPickle code checks the reference count for a little optimization at this point.

所以是的,它的引用计数.但这不是问题.unpickled 的对象将具有正确的引用计数,当引用计数为 1 时,它只会产生一个稍短的 pickle.

So yes, its the reference counts. But not that's not a problem. The objects unpickled will have the correct reference counts, it just produces a slightly shorter pickle when the reference counts are at 1.

现在,我不知道你在做什么,你关心这个.但是你真的不应该假设酸洗同一个对象总是会给你相同的结果.如果不出意外,我希望字典会给您带来问题,因为键的顺序未定义.除非你有保证泡菜每次都一样的 python 文档,否则我强烈建议你不要依赖它.

Now, I don't know what you are you doing that you care about this. But you really shouldn't assume that pickling the same object will always give you the same result. If nothing else, I'd expect dictionaries to give you problems because the order of the keys is undefined. Unless you have python documentation that guarantees the pickle is the same each time I highly recommend you don't depend on it.

这篇关于cPickle - 酸洗同一个对象的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆