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

Jeff Epler jepler at unpythonic.net
Sun Feb 9 15:49:21 EST 2003


On Sun, Feb 09, 2003 at 04:30:09PM +0100, Piet van Oostrum wrote:
> >>>>> Erik Max Francis <max at alcyone.com> (EMF) wrote:
> 
> EMF> Michele Simionato wrote:
> >> Interesting. I would accept this or the "when" proposal. But I am not
> >> sure if other Pythonistas would like a new special symbol "->" only
> >> used in the
> >> ternary operator. Maybe you should think of other case of use for
> >> "->".
> 
> EMF> Since the ? : form is declared unusable by fiat (and I must say I agree,
> EMF> it overloads the use of the colon too much), it seems only reasonable
> EMF> that the two intervening things in the ternary conditional operator be
> EMF> keywords, and both be keywords.  Having one a symbol (whether already
> EMF> used in the language or not) and the other a keyword (whether already
> EMF> used or not) seems unclear.
> 
> It just dawned on me that the 'if' is not really necessary.
> "->" would be a more pythonic operator than "?" I think, because it stands
> out more. And indeed it looks a bit strange to have the other part as a
> keyword.
> 
> What about:
>         condition -> (true part, false part)
> The (,) is not a tuple here but it belongs to the -> and the -> says to
> select one of the expressions based on the condition and evaluate that;
> kind of lazy indexing.

This is not hard to implement given today's bytecode.  
    [evaluate condition]
    JUMP_IF_FALSE false_part_label
    POP_TOP
    [true part]
    JUMP_FORWARD after_expression
false_part_label:
    [false part]
after_expression:
    ...

> 
> We could then also have one for ints rather than bools:
> 
>         i -> [ v_0, v_1, v_2, ... ]
> which would pick v_i and evaluate that.
> Also here the [ ] is not really a list notation but belongs to the ->.

This is hard to implement.  It requires a computed jump which doesn't exist
as far as I know.  It would probably look something like this:
    LOAD_FAST @jump_table0
    [evaluate i]
    BINARY_SUBSCR 
    JUMP_TOP
@jump_table0[0]:
    [evaluate v_0]
    JUMP_FORWARD after_expression
...
after_expression:
    ...

JUMP_TOP does not seem hard to implement, but it is not yet present in the
bytecode as far as I know.

(The dictionary case's code looks exactly the same, except that
@jump_table0 is a dict instead of a list.  Except that these probably have
to be immutable types... is there an immutable dict yet?)

I also agree that the mismatch between
    0 -> ('a', 'b') == 'b'
    0 -> ['a', 'b'] == 'a'
seems like a good argument against the generalization.

Jeff





More information about the Python-list mailing list