[Tutor] toggle idiom?

Lloyd Kvam pythontutor@venix.com
Thu, 09 May 2002 08:45:40 -0400


Paul Sidorsky wrote:
 > perhaps decades.  In fact the only other reasonable alternative I've
 > seen is using C's ternary ?: operator (a = a ? 0 : 1) which is really
 > just a short form of what the OP already had, but since Python has no ?:
 > or equivalent this isn't an option.

As an old C programmer I missed ?: and was interested to find this article by
David Mertz.
http://gnosis.cx/publish/programming/charming_python_13.html
CHARMING PYTHON #13 (20000155) -- Functional Programming in Python --

Dr. Mertz later wrote the following correction for eliminating if statements.
  (<cond1> and [func1()]) or (<cond2> and [func2()]) or ([func3()])[0]

The Python equivalent of (cond)?(e1):(e2) becomes
((cond and [e1]) or [e2])[0]
The e1 and e2 get embedded into lists to cover the case where e1 is false.
Otherwise Python would then go on to evaluate e2 whereas we really want to stop
at e1 when cond is true.  [e1] is always true.  That is even [0] is true.
The [0] at the end of the expression extracts the e1 or e2 result from the
list.  When e1 is true, the code is more reasonable
(cond and e1) or e2

All in all, this is a bit ugly for casual use.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582