Setting hash salt for individual calls [duplicate]

谁说我不能喝 提交于 2020-01-16 21:35:45

问题


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.


回答1:


import hashlib
def getHash(name):
   m = hashlib.md5()
   m.update(name)
   return m.hexdigest()


来源:https://stackoverflow.com/questions/38001874/setting-hash-salt-for-individual-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!