conditional expressions (RE: Loop-and-a-half (Re: Curious assignment behaviour))

Tim Peters tim.one at home.com
Sun Oct 14 22:43:45 EDT 2001


[DeepBlue]
> Much better:
> x = if e1 then (e2) else (e3)

You're apparently responding to an edited reply, and didn't read the thread
from its start:  surrounding parens are required else you don't get this
form of conditional expression at all.  It's not a question of whether to
require surrounding parens or not; the latter isn't an option, due to the
limitations of one-token lookahead parsing (read the thread from the start).

> note that (e2) and (e3) stand for any operation:

e1, e2 and e3 in the original are any expressions (formally, 'test' in the
Python grammar).  I don't know what "operation" means to you, or why you
think adding some parentheses *could* make a semantic difference.  In the
formal syntax, the production for atom changes from

atom: '(' [testlist] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' |
      '`' testlist '`' | NAME | NUMBER | STRING+

to

atom: '(' ([testlist] | cond_expr) ')' | ... [the rest is unchanged]

cond_expr: 'if' test 'else' test 'then' test

> The problem with: x = (if e1 then e2 else e3) + 1 # cool
> is that it lacks potential of generalization.

Generalization to what?  Please be specific.  Stuff like

    x = (if a+b/sqrt(3) then 3**f(5, 3)- 12 else ",".join(list) + ":\n")

is fine.  If you *want* to stick extra parens around the e2 and e3
expressions, that's fine too, but not required.

> x = if e1 then (e2) else (e3)
> does give the user more freedom.

Sorry, I can't see how.

>>     x = (if e1 then e2 else e3 + 1) # cool

> but not clear.

Because?  It's no more or less general than, e.g.,

    x = e1 and e2

today, of which, e.g.,

    x = y + 1 or z + 1

is a specific instance.

>>     x = if e1 then e2 else e3       # SyntaxError

> no reason for error

Read the thread.

> ... [more much the same snipped] ...

> with my idea:
> x = (if (if e1 then (e2) else (e3)) then (e4) else (e5))

This is legit under the proposal.

> or
> x = if (if e1 then (e2) else (e3)) then (e4) else (e5)

But this isn't.

> should be equivalent.
> If the original posting

If you haven't even read the first msg in this thread alone, I shudder to
imagine what "original" means to you <wink>.

> passes Python will have its first confusing moment.
> x = if e1 then (e2) else (e3)
> and
> x = (if e1 then (e2) else (e3))
> should be equivalent and they preserve clarity.

The latter form would be accepted, but not the former (and the former cannot
be accepted, which is a question of parser technology, not of taste).





More information about the Python-list mailing list