Last change
on this file since 1055 was 1055, checked in by wouter, 5 months ago |
#354 added safehash to utilities,
deployed utilities 1.0.8
|
File size:
636 bytes
|
Rev | Line | |
---|
[1055] | 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 | # occurs for some built-in types
|
---|
| 18 | if isinstance(obj, Collection): # list, set, tuple, .iterable
|
---|
| 19 | return hash( tuple ( safehash(elt) for elt in obj ) )
|
---|
| 20 | if isinstance(obj, Dict):
|
---|
| 21 | return safehash( obj.items() )
|
---|
Note:
See
TracBrowser
for help on using the repository browser.