if in expression

Diez B. Roggisch deets at nospam.web.de
Mon Aug 18 09:49:46 CEST 2008

christian2.schmidt at gmx.de schrieb:
> Hi,
> I'm using IronPython to evaluate expressions, so I can't use the
> return statement but have to say it in an one-liner. Using C/C++ I
> could use "cond ? then : else" to have an expression-if, but in Python
> there's no such operator. The "cond and then or else"-trick only seems
> to work for non-false "then"s and is not very readable.
> So is the pythonic way to def iif(cond, then, else_): if cond: return
> then; else: else_; ? But actually this is not the same, because "then"
> and "else_" are evaluated independently of cond...
> What is the right way to have if in an expression?

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_)()


More information about the Python-list mailing list