开发者

Python: how to create a hash of nested containers

[Python 3.1]

I a开发者_StackOverflow社区m trying to create a hash for a container that may have nested containers in it, with unknown depth. At all levels of the hierarchy, there are only built-in types. What's a good way to do that?

Why I need it:

I am caching the result of some calculations in a pickle object (on disk). I would need to invalidate that cached file if the function is called with different parameters (this happens rarely, so I'm not going to save more than one file to disk). The hash will be used to compare the parameters.


If all the containers are tuples, and all the contained objects are hashable, then the main container should be hashable.


You could just serialize the parameters into something like JSON, and use that for the hash.


I would do it with json serialization as a string [and then hash that string if it's still necessary].

from simplejson import dumps

def hash_data(data):
    return hash(dumps(data))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜