Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在functools中使用lru缓存_Python_Lru_Functools - Fatal编程技术网

Python 在functools中使用lru缓存

Python 在functools中使用lru缓存,python,lru,functools,Python,Lru,Functools,我想在我的代码中使用lru_缓存,但出现以下错误: NameError: name 'lru_cache' is not defined 我的代码中有一个导入工具,但这没有帮助 示例代码如下: https://docs.python.org/3/library/functools.html @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2)

我想在我的代码中使用lru_缓存,但出现以下错误:

NameError: name 'lru_cache' is not defined
我的代码中有一个导入工具,但这没有帮助

示例代码如下:

https://docs.python.org/3/library/functools.html

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
https://docs.python.org/3/library/functools.html
@lru_缓存(最大大小=无)
def纤维(n):
如果n<2:
返回n
返回fib(n-1)+fib(n-2)

在使用lru缓存之前,您需要导入它:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

如果您真的只编写了
import functools
,那么这还不够。您需要使用functools import lru\u cache中的
导入
lru\u cache
符号,或者在尝试使用时需要限定名称,如
@functools.lru\u cache


functools模块在这方面没有什么特别之处。所有模块都是这样工作的。当您导入其他模块和使用其他功能时,您可能已经注意到了。

问题中不包括导入行,但它应该是:

from functools import lru_cache
或者,可以将函数decorator更改为:

@functools.lru_cache(maxsize=None)
另一个侧重点是:

如果将maxsize设置为None,则LRU功能将被禁用,缓存将被删除 可以无限制地成长。当maxsize为时,LRU功能的性能最佳 二的幂

文档示例 输出
如果您试图将LRU缓存用于异步函数,它将不起作用。尝试它支持python中的异步类型函数,也可以在缓存函数中使用用户定义的数据类型和基本数据类型作为参数。functools.lru_cache中不支持这一点

我们可以对同一文件中的多个函数使用@functools.lru_cache(maxsize=32)
吗?我们可以对同一文件中的多个函数使用@functools.lru_cache(maxsize=32)吗?
@functools.lru_cache(maxsize=None)
import functools
import urllib
import requests

    @functools.lru_cache(maxsize=32)
    def get_pep(num):
        'Retrieve text of a Python Enhancement Proposal'
        resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
        try:
            with urllib.request.urlopen(resource) as s:
                return s.read()
        except urllib.error.HTTPError:
            return 'Not Found'


    for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
        pep = get_pep(n)
        print(n, len(pep))

    print(get_pep.cache_info())
8 106439
290 59766
308 56972
320 49551
8 106439
218 46795
320 49551
279 48553
289 50882
320 49551
9991 9
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)