Python包,用于使用默认哈希、md5、sha256等对字典进行哈希处理。
项目描述
Dict Hash
Python包,使用默认哈希和sha256对字典进行哈希处理。它支持对Pandas & Polars DataFrame/Series对象、Numba对象和Numpy数组的哈希处理,支持Pandas 1.x和2.x以及Numpy 1.x和2.x的对象。
此外,该库支持可递归哈希的对象。
由于我们发现在野外使用该库主要用于创建缓存库和包装器,我们想向您推荐我们的库,Cache decorator。
为什么我不能只用默认的哈希函数?
在Python中,字典是无法哈希的。这是因为它们是可变对象,因此无法进行哈希。如果您尝试运行hash({})
,您将得到一个TypeError
异常。
我如何安装此软件包?
像往常一样,只需使用pip下载它
pip install dict_hash
使用示例
该软件包提供两个函数:用于生成固定sha256哈希的sha256
函数,以及用于生成使用本地hash
函数的哈希的dict_hash
函数。
使用dict_hash进行会话哈希
从给定的字典中获取会话哈希。
from dict_hash import dict_hash
from random_dict import random_dict
from random import randint
d = random_dict(randint(1, 10), randint(1, 10))
my_hash = dict_hash(d)
一致哈希
从给定的字典中获取一致哈希。支持的方法包括来自hashlib
库的md5
、sha256
、sha1
、sha224
、sha384
、sha512
、sha3_512
、shake_128
、shake_256
、sha3_384
、sha3_256
、sha3_224
、blake2s
、blake2b
。
例如,要从给定的字典中获取sha256哈希
from dict_hash import sha256
from random_dict import random_dict
from random import randint
d = random_dict(randint(1, 10), randint(1, 10))
my_hash = sha256(d)
shake_128
和shake_256
方法公开了长度参数,可以指定哈希摘要的长度。
from dict_hash import shake_128
from random_dict import random_dict
from random import randint
d = random_dict(randint(1, 10), randint(1, 10))
my_hash = shake_128(d, hash_length=16)
近似哈希
所有展示的方法都提供了 use_approximation
参数,允许您在支持的情况下切换到更轻量级的哈希过程,用于各种支持的对象。此过程将随机对提供的对象进行子采样。
目前,我们支持 NumPy、Polars 和 Pandas 对象使用此参数。
from dict_hash import sha256
from random_dict import random_dict
from random import randint
d = random_dict(randint(1, 10), randint(1, 10))
my_hash = sha256(d)
approximated_hash = sha256(d, use_approximation=True)
错误行为
如果哈希函数遇到无法哈希的对象,默认情况下将抛出 NotHashableException
异常。您可以通过设置 behavior_on_error
参数来选择是否抛出此异常或其他选项。您可以选择以下选项:
raise
:抛出NotHashableException
异常。warn
:打印NotHashableWarning
并继续哈希,将无法哈希的对象设置为字符串"Unhashable object"
。ignore
:忽略对象并继续哈希,将无法哈希的对象设置为字符串"Unhashable object"
。
递归对象
在 Python 中,存在递归对象的可能性,例如包含自身的字典。当您尝试对这样的对象进行哈希时,哈希函数将抛出 RecursionError
异常,您可以使用 maximal_recursion
参数来自定义它,默认值为 100
。通常将 RecursionError
视为 NotHashableException
来处理,因此您可以将 behavior_on_error
参数设置为按需处理。
可哈希的
在处理字典中的复杂对象时,您可能需要在该对象中实现类 Hashable
。
以下是一个示例
from dict_hash import Hashable, sha256
class MyHashable(Hashable):
def __init__(self, a: int):
self._a = a
self._time = time()
def consistent_hash(self, use_approximation: bool = False) -> str:
# The use approximation would be useful when the object is too large,
# while in this example it may be a bit pointless.
if use_approximation:
return sha256({
"a": self._a
}, use_approximation=True)
return sha256({
"a": self._a
})
许可证
此软件根据 MIT 许可证分发。
项目详情
dict_hash-1.3.3.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | f20c580e4e1b675d22fd7f44e58b61ee6ab3e6291e8b342f801badc0211e42a6 |
|
MD5 | 35290bb77eda39fdd6d8163d3cbcd301 |
|
BLAKE2b-256 | 5374265d474b72669026beb5dfffbdb8fa92f95708df2fc0ed088aa0030aca47 |