python - 计算一次,缓存结果,并从缓存中无限返回的函数(Python)

标签 python caching python-2.7 generator

我有一个函数执行昂贵的操作并且经常被调用;但是,该操作只需要执行一次 - 它的结果可以被缓存。

我尝试制作一个无限生成器,但没有得到预期的结果:

>>> def g():
...     result = "foo"
...     while True:
...         yield result
... 
>>> g()
<generator object g at 0x1093db230>    # why didn't it give me "foo"?

为什么 g 不是生成器?

>>> g
<function g at 0x1093de488>

编辑:如果这种方法不起作用也没关系,但我需要执行与常规函数完全一样的东西,如下所示:

>>> [g() for x in range(3)]
["foo", "foo", "foo"]

最佳答案

g() 是一个生成器函数。调用它返回生成器。然后您需要使用该生成器来获取您的值。例如,通过循环或调用 next()在上面:

gen = g()
value = next(gen)

请注意,再次调用 g() 将再次计算相同的值并生成一个生成器。

您可能只想使用全局缓存值。将其作为属性存储在 函数上:

def g():
    if not hasattr(g, '_cache'):
        g._cache = 'foo'
    return g._cache

关于python - 计算一次,缓存结果,并从缓存中无限返回的函数(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977645/

相关文章:

python - GPSD 未响应新连接

.htaccess - Google Page Speed 利用浏览器缓存未标记为已解决

database - JPA 缓存与数据库的并发访问保持同步

python - Pandas map lambda 函数的不区分大小写的字典

python - 如何使用 Pandas 数据框删除不在集群中的值?

Python HTML 解析器分页

python - 嵌套字典语法

python - Gensim 3.8.0 到 Gensim 4.0.0

asp.net - 来自 2 个或更多其他缓存项的 CacheDependency。 (ASP.NET MVC3)

Python/请求 : requests. exceptions.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE]