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.
The standard way of doing lazy evaluation in Python is using generators.
BTW. Python also allows generator expressions, so below line will not pre-calculate anything: