For review: PEP 308 - If-then-else expression

Dave Brueck dave at pythonapocrypha.com
Sat Feb 8 17:45:32 EST 2003


On Sat, 8 Feb 2003, Christian Tismer wrote:

> listcomps are leading to "uncomprehensions". I would
> like to see them dropped as a step in the wrong direction.

Not me - when used properly they really add to the readability of my code.
I'm glad we have 'em!

> The proposed syntax is counterintuitive for me by two reasons:
>
> a) control flow in Python always involves special characters.
>     It should at least have some markup at the start and end.

That's part of the problem: you're thinking of control flow in the
assembly-language sense and not in the Python sense. Yes, at the lowest
levels this is a control flow operator (test+jump). But in the
higher-level Python sense this _isn't_ a control flow operator but a
_choice_ operator - and it's much closer to logical operators like "and"
and "or".  It has no special characters because (1) the keywords used have
the saming meaning as always and (2) it's an expression, not a statement.

> b) reading and execution order should match as much as possible.

Why? Do reading and execution order match here?

x.append((x+y, w+z))

Nope! If they did, we would write it something like:

x+y, w+x toTuple applyTo x.append

(assuming name lookups are invisible)

> I consider the if and the colon in "if ... :" as valuable
> markup,

It's useful markup, yes, but for what? For denoting the start of a block,
and even then it's only secondary to the indentation. IIRC the colon was
also in ABC and some usability studies found that indentation + the
preceding colon were more readable than just the indentation, but either
way it is all about denoting the start of a block and has little to do
with 'if' itself.

> Anybody know about how Forth does it? The
> proposal reminded me a litle bit of that:
>
> <cond> if <true-case> else <false-case> then
>
> This is reverse polish notation, which is strange
> by nature.

This made me remember an informal practice with C's conditional operator:
often the test was such that the most likely case was "true" and listed
first, and the PEP proposal allows this same practice to carry over. Not
sure if it matters much, but to me the code:

z = x.Foo() if x else -1

implies (in my own code at least), that I expect that under normal
circumstances x will evaluate to true - IOW x.Foo() is what I expect to
happen most of the time while -1 is more the exceptional case. Given that,
I like the PEP proposal _more_ than the C way because the implication of
what is expected is stronger. I like the similarity between these two:

z = x.Foo()
z = x.Foo() if x else -1 # I expect z to get x.Foo() most of the time

-Dave





More information about the Python-list mailing list