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

James Lu jamtlu at gmail.com
Mon Jun 3 20:57:22 EDT 2019


`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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190603/8af1f47d/attachment.html>


More information about the Python-ideas mailing list