我有一个将(以及其他)字典作为参数的方法。该方法是解析字符串,字典提供了一些子字符串的替换,所以它不必是可变的。
这个函数经常被调用,而且在冗余元素上,所以我认为缓存它会提高它的效率。
但是,正如您可能已经猜到的那样,由于 dict
是可变的,因此不可散列,@functools.lru_cache
无法修饰我的函数。那么我该如何克服呢?
如果它只需要标准库类和方法,则加分。理想情况下,如果它在标准库中存在某种我没见过的 frozendict
,那会让我很开心。
PS:namedtuple
只能在最后使用,因为它需要大量的语法转换。
最佳答案
不要使用自定义哈希字典,而是使用它并避免重新发明轮子!这是一个完全可散列的卡住字典。
https://pypi.org/project/frozendict/
代码:
from frozendict import frozendict
def freezeargs(func):
"""Transform mutable dictionnary
Into immutable
Useful to be compatible with cache
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
args = tuple([frozendict(arg) if isinstance(arg, dict) else arg for arg in args])
kwargs = {k: frozendict(v) if isinstance(v, dict) else v for k, v in kwargs.items()}
return func(*args, **kwargs)
return wrapped
然后
@freezeargs
@lru_cache
def func(...):
pass
代码取自 @fast_cen 的回答
注意:这不适用于递归数据结构;例如,您可能有一个参数是一个列表,它是不可散列的。邀请您进行包装递归,使其深入数据结构并使每个 dict
卡住和每个 list
元组。
(我知道 OP 不再需要解决方案,但我来这里是为了寻找相同的解决方案,所以留给后代)
关于python - 使用带有字典参数的@functools.lru_cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358481/