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

Steven D'Aprano steve at pearwood.info
Mon Jun 3 21:28:27 EDT 2019


On Mon, Jun 03, 2019 at 08:57:22PM -0400, 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

Then the "unless" clause is superfluorous and we can write:

    if condition1 and not condition2 expression

which is another way of saying 

    if condition expression

which has been suggested before in the form:

    expression if condition

and rejected. Please check the archives.


> 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.

Which is precisely how "and" already works.


> # EMPTY
> 
> EMPTY is not actually a real Python value-- it's a value that collapses
> into nothing when used inside a statement expression:
[...]
> EMPTY is neither a constant exposed to the Python runtime nor a symbol.
> It's a compiler-internal value.

I don't even know what you mean by that even after reading your 
examples, sorry.

If I do this:


    var = if False 1 unless False
    print(var)


what happens?


-- 
Steven


More information about the Python-ideas mailing list