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

Andrew Koenig ark at research.att.com
Mon Feb 10 12:53:45 EST 2003


Anders> Ah, but I have a fix in store for that from the last time this was
Anders> discussed: Require parens around the expression.

Anders> Add to the grammar:

Anders> if_expr_list ::=
Anders>              if_expr ( "," if_expr )* [","]

Anders> if_expr ::=
Anders>              "if" comparison ":" if_expr "else" ":" if_expr
Anders>               | expression

Anders> and replace expression_list with if_expr_list in parenth_form, and
Anders> perhaps also in string_conversion and subscription, but not in
Anders> assignment_stmt, return_stmt, yield_stmt etc.

Because this proposal is incomplete, I don't know how to evaluate it;
but I think that if you fill in the details, you will find it
to be larger than mine.

Using the grammar in the compiler, I am proposing to change the following:

Original:

   expr_stmt: testlist (augassign testlist | ('=' testlist)*)
   test: and_test ('or' and_test)* | lambdef

Revised:

   expr_stmt: utestlist (augassign testlist | ('=' testlist)*)
   test: uncond_test | 'if' test ':' test ('elif' test)* 'else' ':' test
   uncond_test: and_test ('or' and_test)* | lambdef
   utestlist: uncond_test (',' test)* [',']

I think the differences between our suggestions would show as follows:

Anders>     x = (if A: B else: C) # legal

Yes.

Anders>     x[if A: B else: C] = D # perhaps legal, or perhaps you need
Anders>     x[(if A: B else: C)] = D # legal

Both legal.

Anders>     print `if A: B else: C` # perhaps legal

Also legal.

Anders>     f(if A: B else: C, D) # legal, D is the second argument to f

Same.

Anders>     x = if A: B else: C  # ILLEGAL

Legal.

Anders>     if if A: B else: C: # VERY ILLEGAL

Legal but silly.

Anders>     if (if A: B else: C): # legal

Yes.

Anders> I think requiring parens like this would be a good idea with all
Anders> syntaxes, lest we want to see
Anders>     if A if B if C else D else E:

This example is obviously illegal on several counts--not the least
of which is the missing colons--so I'm not worried.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list