I'm looking for a way to set python's hash()
salt for individual calls to the function. In the docs, I've only found PYTHONHASHSEED which sets the salt for all calls to hash()
.
However, I need hash
to always get me the same result when called by specific objects, but I don't want to force the entire application to use the same (predictable) salt.
Context: In python2
, I'm using hash
to sort key-value object pairs into indexed buckets. Buckets are stored persistently. This is reversed to fetch the value. Basically, for every pair I do
class PDict(object):
def __init__(self, bucket_count, bucket_store_path):
self._path, self.bucket_count = \
self._fetch_or_store_metadata(bucket_store_path, bucket_count)
def __setitem__(self, key, value):
bucket_index = (hash(key)&0xffffffff) % self.bucket_count
self.buckets[bucket_index][key] = value
self._store_bucket(bucket_index)
def __getitem__(self, key):
bucket_index = (hash(key)&0xffffffff) % self.bucket_count
return self._fetch_bucket(bucket_index)[key]
This requires hash
to always get me the same result per instance, across interpreter invocation.