PEP-able? Expressional conditions

Kay Schluehr kay.schluehr at gmx.net
Wed Sep 7 06:29:26 EDT 2005


One of the main reasons Pythons anonymous function lambda is considered
to be "broken" is Pythons disability to put statements into expressions
and support full functionality. Many attempts to improve lambdas syntax
had also been attempts to break the expression/statement distinction in
one or the other way. None of this suggestions have ever been
successfull in solving severe problems caused by Pythons indentation
syntax and I guess they will never succeed. On the other hand I do not
see immediately the necessaty to support the full range of Python
constructs in small anonymous functions that are dedicated to fit into
one line.

Instead of pushing statements into expressions one can try to do it the
other way round and model expressions with the functionality of
statements. The most important use-cases are assignments and
conditions. I want to consider conditions only.

In Python conditional statements have the form:

if COND_1:
   BLOCK_1
elif COND_2:
   BLOCK_2
...
else:
   BLOCK_n

Before turning this kind of statement into an expression we have to
restrict the BLOCKs to expressions:

if COND_1:
   EXPR_1
elif COND_2:
   EXPR_2
...
else:
   EXPR_n

Since the conditional statement is traversed sequentially we can
transform it into a sequence of (COND,EXPR) pairs. Finally we have to
recover the conditional semantics.

I want to propose a new associative binary operator that acts on
(COND,EXPR) pairs like a projection on the second EXPR argument of a
pair in case of COND evaluated True.

This function works much like

def cond(pair1, pair2):
    COND1,EXPR1 = pair1
    if COND1:
        return EXPR1
    try:
        COND2,EXPR2 = pair2
        if COND2:
            return EXPR2
    except TypeError:
        return pair2


Alternative syntax proposals:

(a)   (COND1,EXPR1) || (COND2,EXPR2)
(b)   (COND1,EXPR1) case (COND2,EXPR2)
(c)   (COND1,EXPR1) owise (COND2,EXPR2)
(d)   (COND1,EXPR1) ? (COND2,EXPR2) 

Regards,
Kay




More information about the Python-list mailing list