[lang-ref] ( null_coalescing ) ( python )

@pytest.mark.parametrize(
    'a, expected',
    [
        (None, 'not set'),
        (3, 3),
        (0, 0),
    ],
)
def test_null_coalescing(a, expected):
    # x = 'not set' if a is None else a

    # Want: x = a ?? "not set" (C#/Swift)
    #    or x = a ?: "not set" (so-called Elvis operator in Kotlin/Groovy)
    # Python has no dedicated operator, but equivalent expressions exist.

    # ternary operator like
    x = 'not set' if a is None else a
    assert x == expected

    # For readability, simply..
    if a is None:
        x = 'not set'
    else:
        x = a

    assert x == expected
@pytest.mark.parametrize(
    'a, expected',
    [
        (None, -1),
        (3, 3),
        (0, 0),
    ],
)
def test_null_coalescing_alternative2(a, expected):
    # Same logic in a single expression (less readable for me).
    x = -1 if a is None else a
    assert x == expected
@pytest.mark.parametrize(
    'a, expected',
    [
        (None, -1),
        (3, 3),
        (0, -1), # this is not what I want
    ],
)
def test_null_coalescing_alternative3(a, expected):
    # deprecated for me: `or` uses truthiness, not a None check.
    x = a or -1
    assert x == expected