(PEP-308) Python's Conditional Selection Operators
Terry Reedy
tjreedy at udel.edu
Sat Feb 15 12:12:25 EST 2003
Addendum (2003 Feb 15)
"Terry Reedy" <tjreedy at udel.edu> wrote in message
news:dTOdndgPZ8gTG9CjXTWcqw at comcast.com...
...
> In logic, math, and computing science, 'and' and 'or' have
well-known
> standard meanings as logical operators, either strict or
By standard, I meant 'typical, most common' rather than 'technical
committee blessed'.
[much snip]
> Selective 'and' and 'or'
> ------------------------
...
> The reversed expressions '(a and b) or c' and '(not a or b) and c'
are
> the most relevant to PEP-308 and the quest for an 'if a then b else
c'
> ternary. When a is False, both select c. When a is True, the first
> selects True b while the second selects False b. So if we know the
> truth value of one of the selection targets, there is an and/or
> combination that gives the right answer. For instance, if x then
> x.val else 0 == (x or 0) and x.val.
Python FAQ 4.16 says
In many cases you can mimic a?b:c with "a and b or c" , but ...
but does not mention the "(not a or b) and c" mimic that may work when
the other does not (ie, when b is known False instead of known True).
Question: did anyone know about this alternative (but keep pretty
quiet about it)?
Observation: By plugging part of the hole in the and/or form, the
or/and form makes an exact replacement less necessary. On the other
hand, by still leaving a small hole (when neither b nor c have a known
single truth value), it may make having one form that always works
seem more desirable.
> For the general case, the two expressions combine to exactly match
'if
> a then b else c':
> (a and b) or ((not a or b) and c) ==
> (not a or b) and ((a and b) or c).
If a or b have side effects, their possible double evaluation makes
the match not quite exact, even if the overt outcome is still the
same.
> However, these are sufficiently baroque that most any of the current
> or proposed alternatives should be better.
Terry J. Reedy
More information about the Python-list
mailing list