Python惰性评估器 [英] Python lazy evaluator

查看:59
本文介绍了Python惰性评估器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有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惰性评估器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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