Avoid or delay evaluation of things which may not be used
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()
BTW. Python also allows generator expressions, so below line will not pre-calculate anything:
g = (10**x for x in xrange(100000000))
You can use apartial
(-ly applied function):
import random
def foo(x):
print x
return x
from functools import partial
print random.choice((partial(foo,'spam'), partial(foo,'eggs')))()
When you need a dict with defaults you can use a defaultdict
from collections import defaultdict
d = defaultdict(somedefault)
print d[k] # calls somedefault() when the key is missing
Python is not a lazy language and there is no special support for laziness. When you want to generate a individual value later, you must wrap it in a function. In addition, generators
can be used to generate a sequence of values at a later time.