【发布时间】:2017-10-11 15:29:39
【问题描述】:
我试图仅通过函数的第一个参数来缓存函数expand。出于缓存的目的,我不关心其他参数的值。
由于其他参数是 dicts,它们不可缓存,所以我定义了一个类来包含这些参数,其哈希值始终返回 0,因此缓存函数应该忽略它。
我在下面添加了一些缩减代码。我使用的是 Python 3.5.2 版。
class Node:
def __init__(self, value):
self.value = value
def expand(self, a1, a2):
return '{},{},{}'.format(self.value, a1, a2)
class ExpandArgs:
def __init__(self, a1, a2):
self.a1 = a1
self.a2 = a2
def __hash__(self):
# We don't care about the hash, but it's required for caching
return 0
@functools.lru_cache(maxsize=None) # hash of args is always 0, so it should be ignored, and the hash of node should be used as the cache key
def expand(node, args):
a1 = args.a1
a2 = args.a2
return node.expand(a1, a2)
e1 = ExpandArgs({}, {})
e2 = ExpandArgs({}, {})
print(hash(e1)) # 0
print(hash(e2)) # 0
node = Node(123)
print(expand.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
expand(node, e1)
print(expand.cache_info()) # CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)
expand(node, e2)
print(expand.cache_info()) # CacheInfo(hits=0, misses=2, maxsize=None, currsize=2)
expand(node, e1)
print(expand.cache_info()) # CacheInfo(hits=1, misses=2, maxsize=None, currsize=2)
expand(node, e2)
print(expand.cache_info()) # CacheInfo(hits=2, misses=2, maxsize=None, currsize=2)
由于hash(e1) == hash(e2),我预计对expand() 的第二次调用会命中e1 的缓存值,但它没有命中。
为什么上述代码没有 1 次缓存未命中和 3 次缓存命中?
【问题讨论】:
-
我想我可以这样做 stackoverflow.com/a/32655449/3173255