Last change
on this file since 1057 was 1057, checked in by wouter, 5 months ago |
#354 hashcode fixes.Apparently a Dict is a Collection in python
|
File size:
706 bytes
|
Line | |
---|
1 |
|
---|
2 |
|
---|
3 | from collections.abc import Iterator
|
---|
4 | from itertools import tee
|
---|
5 | from typing import Tuple, List, Collection, Dict
|
---|
6 |
|
---|
7 | def safehash(obj)->int:
|
---|
8 | '''
|
---|
9 | Tool to take a hash of an object in a safe way.
|
---|
10 | The idea is that it intercepts non-hashable types
|
---|
11 | and works around it.
|
---|
12 | '''
|
---|
13 | try:
|
---|
14 | # first try the dumb way, because the safe way is expensive
|
---|
15 | return hash(obj)
|
---|
16 | except TypeError:
|
---|
17 | # we must test dict first, as Dict IS a collection in python ?!
|
---|
18 | if isinstance(obj, Dict):
|
---|
19 | return safehash( obj.items() )
|
---|
20 | # occurs for some built-in types
|
---|
21 | if isinstance(obj, Collection): # list, set, tuple, .iterable
|
---|
22 | return hash( tuple ( safehash(elt) for elt in obj ) )
|
---|
Note:
See
TracBrowser
for help on using the repository browser.