python - pickle 过程是确定性的吗?

标签 python pickle memoization

对于某个输入值,Pickle 是否总是产生相同的输出?我想在对内容相同但插入/删除历史记录不同的字典进行 pickle 时可能会出现问题。我的目标是使用 Pickle 和 SHA1 创建函数参数的“签名”,以实现记忆化。

最佳答案

I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.

右:

>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})
False

另请参阅:pickle.dumps not suitable for hashing

My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.

这有很多基本问题。想出一个正确映射相等性的对象到字符串的转换是不可能的——想想对象标识的问题:

>>> a = object()
>>> b = object()
>>> a == b
False
>>> pickle.dumps(b) == pickle.dumps(a)
True

根据您的具体要求,您可以将对象层次结构转换为可以散列的对象层次结构:

def hashablize(obj):
    """Convert a container hierarchy into one that can be hashed.
    
    Don't use this with recursive structures!
    Also, this won't be useful if you pass dictionaries with
    keys that don't have a total order.
    Actually, maybe you're best off not using this function at all."""
    try:
        hash(obj)
    except TypeError:
        if isinstance(obj, dict):
            return tuple((k, hashablize(v)) for (k, v) in sorted(obj.iteritems()))
        elif hasattr(obj, '__iter__'):
            return tuple(hashablize(o) for o in obj)
        else:
            raise TypeError("Can't hashablize object of type %r" % type(obj))
    else:
        return obj

关于python - pickle 过程是确定性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/985294/

相关文章:

python - 在 python 中限制 raw_input

Python:确保我的类只使用最新的协议(protocol)进行 pickle

python - 使用协议(protocol) 2 : Python3->2 data 进行 pickle

python - 如何使用多个分类变量以 Python R 风格创建预测模型

python - 为什么此代码在重复调用函数后会引发错误?

functional-programming - 为什么 Erlang 函数默认不被内存?

c++ - 我如何记住这种递归关系?

functional-programming - 在 Racket 中编写缓存函数

python - 如何在atom上运行python脚本?

python - 从 pickle 加载的 HMM 看起来未经训练