Can I use a conditional in a variable declaration?
Sun Mar 19 05:33:00 CET 2006
volcs0 at gmail.com writes:
> a = (if a == "yes": "go ahead": "stop")
> is there such a form in Python? I tried playing around with lambda
> expressions, but I couldn't quite get it to work right.
This has been the subject of huge debate over the years. The answer
is Python doesn't currently have it, but it will be added to a coming
version: See http://www.python.org/doc/peps/pep-0308/
To do it in the most general way with lambda expressions, use (untested):
a = (lambda: iffalse_expression,
That makes sure that only one of the target expressions gets evaluated
(they might have side effects).
There are various more common idioms like
a = (condition and iftrue_expression) or iffalse_expression
which can go wrong and evaluate both expressions. It was a bug caused
by something like this that led to conditional expressions finally
being accepted into Python.
More information about the Python-list