特别是在使用递归代码时,lru_cache
有了很大的改进。我确实理解缓存是一个存储必须快速提供的数据的空间,并且可以避免计算机重新计算。
functools 中的 Python lru_cache
如何在内部工作?
我正在寻找一个具体的答案,它是否像 Python 的其他部分一样使用字典?它只存储 return
值吗?
我知道 Python 大量构建在字典之上,但是,我找不到这个问题的具体答案。希望有人可以为 StackOverflow 上的所有用户简化此答案。
最佳答案
functools
源代码可在此处获得:https://github.com/python/cpython/blob/master/Lib/functools.py
lru_cache
使用 _lru_cache_wrapper
装饰器(带有参数模式的 python 装饰器),它有一个 cache
字典在上下文中它保存被调用函数的返回值(每个修饰函数都有自己的缓存字典)。字典键是使用参数中的 _make_key
函数生成的。在下面添加了一些大胆的评论:
# ACCORDING TO PASSED maxsize ARGUMENT _lru_cache_wrapper
# DEFINES AND RETURNS ONE OF wrapper DECORATORS
def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
# Constants shared by all lru cache instances:
sentinel = object() # unique object used to signal cache misses
cache = {} # RESULTS SAVES HERE
cache_get = cache.get # bound method to lookup a key or return None
# ... maxsize is None:
def wrapper(*args, **kwds):
# Simple caching without ordering or size limit
nonlocal hits, misses
key = make_key(args, kwds, typed) # BUILD A KEY FROM ARGUMENTS
result = cache_get(key, sentinel) # TRYING TO GET PREVIOUS CALLS RESULT
if result is not sentinel: # ALREADY CALLED WITH PASSED ARGS
hits += 1
return result # RETURN SAVED RESULT
# WITHOUT ACTUALLY CALLING FUNCTION
misses += 1
result = user_function(*args, **kwds) # FUNCTION CALL - if cache[key] empty
cache[key] = result # SAVE RESULT
return result
# ...
return wrapper
关于python - Lru_cache(来自 functools)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883177/