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'
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'
I'm looking for a Pythonic way to refactor examples like the above to evaluate lazily.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…