Python function evaluation model

I was looking at an article on Peter Norvig's website where he was trying to answer the following question (that's not my question by the way) "Is it possible to do an equivalent (test result: alternatives) in Python?"

here is one of the options he listed,

def if_(test, result, alternative=None):
    "If test is true, 'do' result, else alternative. 'Do' means call if callable."
    if test:
        if callable(result): result = result()
        return result
    else:
        if callable(alternative): alternative = alternative()
        return alternative

      

And here's an example of use.

>>> fact = lambda n: if_(n <= 1, 1, lambda: n * fact(n-1))
>>> fact(6)
720

      

I understand how it works (I think), but I was just playing around with the code and decided to see what happens when I change the third argument in the definition of "fact" above n * fact (n-1), i.e. change it to not called expression. At startup, the interpreter goes into an infinite loop. I have a pretty good idea of ​​why this is happening, that is, the if_ function returns back the same expression it receives. But what is the type of this expression? What exactly is going on here? I'm not looking for a detailed explanation, but just for some pointers to the python scoring model that might help me understand.

Thanks!

+2


a source to share


1 answer


The reason the loop never ends when you change fact

to n * fact(n-1)

means you n * fact(n-1)

must evaluate first (as the third argument for if

). Evaluating it leads to another call fact

, ad infinitum (since there is no more base case to stop it).

Previously, you were passing a function object ( lambda

) that would not be evaluated before the body if

, and its result would be tested through test

.



This is known (I believe) as eager evaluation, where function arguments are evaluated before they are passed to the function. In a lazy evaluation scheme, arguments will not be evaluated until they are used in the body of the function.

+4


a source







All Articles