[lang-ref] ( null_coalescing ) ( python )
def test_null_coalescing():
#
# Want: x = a ?? -1 (C#/Swift)
# or x = a ?: -1` (so-called Elvis operator in Kotlin/Groovy)
# But there is no compact syntax in Python, so use a verbose one.
pytest.skip('Not supported')
@pytest.mark.parametrize(
'a, expected',
[
(None, -1),
(3, 3),
(0, 0),
],
)
def test_null_coalescing_alternative1(a, expected):
# Want: x = a ?? -1 (C#/Swift)
# or x = a ?: -1` (so-called Elvis operator in Kotlin/Groovy)
# But there is no compact syntax in Python, so use a verbose one.
if a is None:
x = -1
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