rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
The body of a function is not evaluated until it is executed. At the start, rec_fn
has no value. The contents of the lambda is just some expression that has some function call on some variable rec_fn
. It won't fail yet because the function isn't executed yet. The new lambda function is then assigned to the variable rec_fn
followed by a call to the function. Now since the function is being executed, it will go through the motions up to the function call. The expression is 10==11 or rec_fn()
. It's an or
expresison so the left hand side is evaluated. 10==11
is False so it must evaluate the right hand side which is a function call to some function (or other callable object) rec_fn
. At that point, rec_fn
is assigned to the function we just created (itself) so it gets called (recursively). And so on. It is equivalent to:
def rec_fn():
return 10==11 or rec_fn()
Lambdas can be written using as many parameters as necessary. In the case of lambda: ...
, there are none specified so it's a "function that takes no arguments."
Just remember, functions (and by extension, lambdas) are first class objects. You can pass them around like any other object and store them into other variables.
rec_fn = lambda: ...
is fine because you've defined a lambda function and stored it into the variable rec_fn
. It can be called by using that name rec_fn()
like you would any other function.
rec_fn() = lambda: ...
on the other hand fails because you cannot assign anything to the result of the function call rec_fn()
.
Defining a function this way is much different than a normal function definition:
def rec_fn2(): # here you may use the parens with the name to indicate it takes no arguments
... # unlike in the lambda assignment above
Just try to remember the difference.