if in expression

Diez B. Roggisch deets at nospam.web.de
Mon Aug 18 04:37:11 EDT 2008


Hrvoje Niksic schrieb:
> "Diez B. Roggisch" <deets at nospam.web.de> writes:
> 
>> Since python 2.5, it is
>>
>> <then_value> if <cond> else <else_value>
>>
>> If you want lazy evaluation, you can use lambdas:
>>
>> iif(cond, lambda: then, lambda: else_)()
> 
> Your code uses "iif" and attempts to evaluate a tuple; could you post
> an example that works?

> I ask because it's not clear what you mean by lazy evaluation in this
> context.  The ternary "if" expression introduced in Python 2.5 only
> evaluates then_value or else_value depending on the outcome of cond.
> How is that different than using a lambda?


If iif is defined as this:

def iif(cond, then, else_):
     if cond:
        return then
     else:
        return else_

you have the problem that "then" and "else_" get evaluated *before* they 
  get passed. So for example this factorial function will fail with too 
deep recursion error:

def f(n):
    return iif(n> 1, n * f(n-1), 1)

But if you do it like this, the then and else_ will be functions that 
get returned and then they need to be called to be acutally evaluated:

def f(n):
    return iif(n> 1, lambda: n * f(n-1), lambda: 1)()


Diez



More information about the Python-list mailing list