python - Lru_cache(来自 functools)如何工作?

标签 python python-3.x numpy caching lru

特别是在使用递归代码时,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/

相关文章:

python - 当且仅当嵌套对象中存在特定键时才需要 JSON 模式条件

python - 尝试在 python 中一次搜索 2 个字符

python - 在 python 上反转 3D 网格

python - 哪个 XML 解析器具有最易读的错误报告?

python - Twisted 和 smtp tls 客户端

python - 同时填充 Pandas 数据框中相关列中的缺失值

python - 在 Python 中求解线性整数方程组

numpy - 我怎样才能重复一个数组m次

python - 如何在 python 中保存来自 selenium 和 opencv 的部分屏幕截图

python - 如何从二进制文件中读取无符号整数?