[Python-ideas] `if-unless` expressions in Python

MRAB python at mrabarnett.plus.com
Mon Jun 3 21:23:23 EDT 2019


On 2019-06-04 01:57, James Lu wrote:
> `if-unless` expressions in Python
> 
>      if condition1 expr unless condition2
> 
> is an expression that roughly reduces to
> 
>      expr if condition1 and not condition2 else EMPTY
> 
> 
> This definition means that expr is only evaluated if `condition1 and not 
> condition2` evaluates to true. It also means `not condition2` is only 
> evaluated if `condition1` is true.
> 
> # EMPTY
> 
> EMPTY is not actually a real Python value-- it's a value that collapses 
> into nothing when used inside a statement expression:
> 
>      print([
>        if False never_called() unless False,
>        if False never_called() unless False,
>      ]) # => []
> 
>      print([
>        3,
>        if False never_called() unless False,
>        if False never_called() unless False,
>        2,
>        if True 5 unless False,
>        4
>      ]) # => [3, 2, 5, 4]
> 
> 
> EMPTY is neither a constant exposed to the Python runtime nor a symbol. 
> It's a compiler-internal value.
> 
> # Use cases
> 
> Assertions.
> 
>      assert if condition1 predicate(object) unless condition2
> 
> (This would be more readable with assert expressions.)
> 
> Macros.
> 
> # Equivalent syntax in existing Python
> 
> As a statement:
> 
> if condition1 and not condition2: predicate(object)
> 
> predicate(object) if condition1 and not condition2
> 
> # Backward compatibility
> 
> The `unless` word is only recognized as special inside `if-unless` 
> statements. The continued use of the word as a variable name is discouraged.
> 
-1
I find it very difficult to understand.

For statements we already have the 'if' statement, as above.

Within expressions such as a list comprehension, it would be much 
clearer IMHO to have a ternary 'if' with 'pass':

     expr if condition else pass

No new reserved words needed.


More information about the Python-ideas mailing list