I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the pr
Dietrich's answer is a good one, but I just want to add that the simplest form of deferred evaluation is the if
statement:
if True:
x = 5
else:
x = y # huh? what is y?
This code parses and runs correctly, although the else
clause makes no sense - y
is undefined. The else
clause is only being parsed - so it should be valid Python syntactically. This can be actually used for some simple code:
if stuff:
print stuff.contents
else:
print "no stuff"
In a strongly typed language this wouldn't work, because to type stuff.contents
requires stuff
to be of a certain type that has a contents
attribute. In Python, because of the deferred evaluation of the statements in if
, this isn't necessarily true. stuff
can be None
which obviously has no attributes, and the interpreter will just take the else
clause without executing the first. Hence this is valid Python and even an idiom, that makes code simpler.
Reference discussion