是否有一个装饰器来简单地缓存函数的返回值? [英] Is there a decorator to simply cache function return values?

查看:77
本文介绍了是否有一个装饰器来简单地缓存函数的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

@property
def name(self):

    if not hasattr(self, '_name'):

        # expensive calculation
        self._name = 1 + 1

    return self._name

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

I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)

PS的实际计算不依赖于可变值

PS the real calculation doesn't depend on mutable values

推荐答案

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

Starting from Python 3.2 there is a built-in decorator:

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

装饰器将带有回忆的可调用函数包装在一起的函数,该函数最多可保存最近调用的最大大小.当使用相同的参数定期调用昂贵的或I/O绑定的函数时,可以节省时间.
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缓存示例:

@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,下面是其他兼容的备注库的列表:


If you are stuck with Python 2.x, here's a list of other compatible memoization libraries:

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

这篇关于是否有一个装饰器来简单地缓存函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆