Skip to content

Instantly share code, notes, and snippets.

@blazetopher
Last active December 19, 2015 05:09
Show Gist options
  • Save blazetopher/5901859 to your computer and use it in GitHub Desktop.
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.
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