For review: PEP 308 - If-then-else expression
David Eppstein
eppstein at ics.uci.edu
Fri Feb 7 16:43:41 EST 2003
In article <yu994r7fhmnh.fsf at europa.research.att.com>,
Andrew Koenig <ark at research.att.com> wrote:
> Some people would write something like this:
>
> strs = []
> for i in ints:
> if i < 0:
> strs.append("?")
> else:
> strs.append(str(i))
>
> but others (including me) would like to be able to write this:
>
> strs = [("?" if i < 0 else str(i)) for i in ints]
For both of your versions, I'd reverse the order, since str(i) seems to
be the primary intended result and "?" a fallback for unusual cases:
strs = [(str(i) if i >= 0 else "?") for i in ints]
I haven't yet thought whether I want to vote for GvR's proposal, but
one advantage of it to me is that it does emphasize the primary result
(the if clause), and de-emphasize the logic of how you choose that
result.
So, when reading such code, you can more quickly see what type of object
you're going to get: as soon as I see "str(i) if..." I can tell that the
result will be a stringified int, except for some less-common cases
where it will likely be something else resembling that. On the other
hand, for the C syntax (or similar counterproposals in this thread), the
first thing you see is the i>=0 comparison, which I don't think is the
most important feature of the expression -- you have to read more of the
expression to have any idea what kind of value it will produce.
--
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