是否有Python方式封装惰性函数调用,从而在第一次使用函数f()时调用了先前绑定的函数g(Z),而在后续调用f()中返回了缓存的值?
请注意,记忆可能并不完美.
我有:
f = g(Z) if x: return 5 elif y: return f elif z: return h(f)该代码有效,但我想对其进行重组,以便仅在使用该值的情况下调用g(Z).我不想更改g(...)的定义,并且Z有点大.
我认为f必须是一个函数,但事实并非如此.
解决方案无论您是寻求缓存还是懒惰的评估,我都有些困惑.对于后者,请查看Alberto Bertogli的模块 lazy.py .
Is there a Pythonic way to encapsulate a lazy function call, whereby on first use of the function f(), it calls a previously bound function g(Z) and on the successive calls f() returns a cached value?
Please note that memoization might not be a perfect fit.
I have:
f = g(Z) if x: return 5 elif y: return f elif z: return h(f)The code works, but I want to restructure it so that g(Z) is only called if the value is used. I don't want to change the definition of g(...), and Z is a bit big to cache.
EDIT: I assumed that f would have to be a function, but that may not be the case.
解决方案I'm a bit confused whether you seek caching or lazy evaluation. For the latter, check out the module lazy.py by Alberto Bertogli.
更多推荐
Python惰性评估器
发布评论