避免或延迟对可能不使用的事物的评估 [英] Avoid or delay evaluation of things which may not be used
问题描述
如何在Python中实现惰性评估?一些简单的例子:
How can lazy evaluation be achieved in Python? A couple of simple examples:
>>> def foo(x):
... print(x)
... return x
...
>>> random.choice((foo('spam'), foo('eggs')))
spam
eggs
'eggs'
上面,我们真的不需要评估该元组的所有项目来选择其中一个.在下面,除非实际在字典中缺少查找键,否则实际上不需要计算默认的foo()
:
Above, we didn't really need to evaluate all the items of this tuple, in order to choose one. And below, the default foo()
didn't really need to be computed unless the lookup key was actually missing from the dict:
>>> d = {1: "one"}
>>> d.get(2, foo("default"))
default
'default'
>>> d.get(1, foo("default"))
default
'one'
我正在寻找一种Python的方式来重构像上面的例子来懒惰地求值.
I'm looking for a Pythonic way to refactor examples like the above to evaluate lazily.
推荐答案
The standard way of doing lazy evaluation in Python is using generators.
def foo(x):
print x
yield x
random.choice((foo('spam'), foo('eggs'))).next()
顺便说一句. Python还允许生成器表达式,因此下面的行将不会预先计算任何内容:
BTW. Python also allows generator expressions, so below line will not pre-calculate anything:
g = (10**x for x in xrange(100000000))
这篇关于避免或延迟对可能不使用的事物的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!