Vote on PEP 308: Ternary Operator
Andrew Dalke
adalke at mindspring.com
Mon Mar 3 23:10:27 EST 2003
Sabby and Tabby:
> data = (hasattr(s, 'open') and s.readlines() or s.split())
> z = 1.0 + (abs(z) < .0001 and 0 or z)
> return (len(s)<10 and linsort(s) or qsort(s))
What if s.readlines() returns [] ?
>>> import StringIO
>>> class MyStringIO(StringIO.StringIO):
... def open(self):
... pass
...
>>> s = MyStringIO("")
>>> data = (hasattr(s, 'open') and s.readlines() or s.split())
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: MyStringIO instance has no attribute 'split'
>>>
The second case with the "and 0" *always* returns 1.0 + z, as in
>>> z = 0.0001
>>> z = 1.0 + (abs(z) < .0001 and 0 or z)
>>> z
1.0001
>>>
If linsort returns None or some other false value then the
third case also my call qsort, eg, when len(s) == 0.
The and/or mechanism is not a general catch-all for a ternary
if/else operator. It should be used judiciously, if at all.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list