For review: PEP 308 - If-then-else expression
David Eppstein
eppstein at ics.uci.edu
Sat Feb 8 01:11:59 EST 2003
In article <mailman.1044675560.14943.python-list at python.org>,
Carel Fellinger <carel.fellinger at chello.nl> wrote:
> > Carel> The proposal as is looks reasonable to me, it would clean up
> > Carel> those few uses of (a and b or c) that I have in my code.
> >
> > Would you mind showing us some concrete examples? I think that
> > some real code examples would be quite useful to the discussion.
>
> Bumbers, it has been quit some time since I used that construct, and
> it's not as easily spotted as C's ternary operator either. I've found
> one example, others are made up.
As far as I can remember, the last time I wanted to use that construct,
I couldn't, because b was false. Hah! Found it:
if i < 0:
col = None
else:
col = cols[i]
Here cols[i] is a string, and I didn't want to assume that it is always
nonempty, so the and-or construct doesn't work. I think this would be a
good candidate for a one-liner:
col = cols[i] if i >= 0 else None
I also just grepped through the same small project (1000 lines), and
found two examples where I did use the construct. In both cases I used
"x and 1 or 0" to normalize a boolean. Of course that could have been
"not not x" or better (in 2.3) "bool(x)"...
To me, the fact that people are treating "a and b or c" as a standard
idiom is a sign that we should replace it with something less likely to
be buggy and more understandable.
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list