对于某个输入值,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/