forked from doctaphred/phrecipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreeze.py
48 lines (38 loc) · 1.58 KB
/
freeze.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from collections.abc import Iterable, Mapping, Set
def frozen(struct):
"""Return an immutable, hashable version of the given data structure.
Iterators (including generators) are hashable but mutable, so they
are evaluated and returned as tuples---if they are infinite, this
function will not exit.
"""
if isinstance(struct, Mapping):
return frozenset((k, frozen(v)) for k, v in struct.items())
if isinstance(struct, Set):
return frozenset(frozen(item) for item in struct)
if isinstance(struct, Iterable): # Includes iterators and generators
return tuple(frozen(item) for item in struct)
hash(struct) # Raise TypeError for unhashable objects
return struct
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)))