python - 是否有一个装饰器可以简单地缓存函数返回值?

考虑以下几点:

@property
def name(self):

    if not hasattr(self, '_name'):

        # expensive calculation
        self._name = 1 + 1

    return self._name

我是新手,但我认为缓存可以分解为装饰器。只是我没有找到喜欢的;)

PS 真正的计算不依赖于可变值

最佳答案

从 Python 3.2 开始有一个内置的装饰器:

@functools.lru_cache(maxsize=100, typed=False)

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

用于计算的 LRU 缓存示例 Fibonacci numbers :

from functools import lru_cache

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

>>> print([fib(n) for n in range(16)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> print(fib.cache_info())
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

如果您被 Python 2.x 困住,这里是其他兼容的内存库的列表:

  • functools32 | PyPI | Source code
  • repoze.lru | PyPI | Source code
  • pylru | PyPI | Source code
  • backports.functools_lru_cache | PyPI | Source code

https://stackoverflow.com/questions/815110/

相关文章:

python - Pandas 在每组中获得前 n 条记录

python - 通过比较两个绝对路径获取相对路径

linux - 为什么 docker 有能力运行不同的 linux 发行版?

c - stdout 和 STDOUT_FILENO 的区别

c - 分离与可连接 POSIX 线程

linux - 从命令行将文本附加到文件而不使用 io 重定向

linux - 当我启动 apache 并继续杀死我的机器时,如何防止产生大量的 apache 进程

python - 遍历python中的对象属性

python - 在 Python 中,使用 argparse,只允许正整数

python - 在 matplotlib 中设置颜色条范围