Last active
December 19, 2015 05:09
-
-
Save blazetopher/5901859 to your computer and use it in GitHub Desktop.
Function to recursively hash an item of any (nearly) type, including full objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Hashable | |
try: | |
import numpy as np | |
has_np=True | |
except ImportError: | |
has_np=False | |
def hash_any(value, hv=None): | |
hv = hv or 0 | |
if value is None or isinstance(value, Hashable): | |
hv = hash(value) ^ hv | |
elif has_np and np.isscalar(value): | |
hf = hash(value) ^ hv | |
elif isinstance(value, (list, tuple, set)): | |
for x in value: | |
hv = hash_any(x, hv) | |
elif isinstance(value, dict): | |
for k,v in value.iteritems(): | |
hv = hash_any(k, hv) | |
hv = hash_any(v, hv) | |
elif isinstance(value, slice): | |
# Hash a tuple of the slice components | |
hv = hash((value.start, value.stop, value.step)) ^ hv | |
elif isinstance(value, object): | |
hv = hash_any(value.__dict__, hv) | |
return hv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment