def hashified(struct, use_none=False):
"""Return a hashable version of the given data structure.
If use_none is True, returns None instead of raising TypeError for
unhashable types: this will serve as a bad but sometimes passable
hash.
See also functools._make_key, which might be a better choice.
"""
try:
hash(struct)
except TypeError:
pass
else:
# Return the original object if it's already hashable
return struct
if isinstance(struct, Mapping):
return frozenset((k, hashified(v)) for k, v in struct.items())
if isinstance(struct, Set):
return frozenset(hashified(item) for item in struct)
if isinstance(struct, Iterable):
return tuple(hashified(item) for item in struct)
if use_none:
return None
raise TypeError('unhashable type: {.__name__!r}'.format(type(struct)))
评论列表
文章目录