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

2rs*_*2ts 0 python caching generator python-2.7

我有一个执行昂贵操作的功能,经常被调用; 但是,操作只需执行一次 - 其结果可以缓存.

我尝试制作一个无限的发电机,但我没有得到我预期的结果:

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

为什么不是g发电机?

>>> g
<function g at 0x1093de488>
Run Code Online (Sandbox Code Playgroud)

编辑:如果这种方法不起作用,这很好,但我需要的东西与常规函数完全相同,如下所示:

>>> [g() for x in range(3)]
["foo", "foo", "foo"]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

g()是一个发电机功能.调用它返回生成器.然后,您需要使用该生成器来获取您的值.例如,通过循环或通过调用next()它:

gen = g()
value = next(gen)
Run Code Online (Sandbox Code Playgroud)

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

您可能只想使用全局来缓存该值.把它作为一个属性的功能可以工作:

def g():
    if not hasattr(g, '_cache'):
        g._cache = 'foo'
    return g._cache
Run Code Online (Sandbox Code Playgroud)