This is my favorite so far. But maybe replace if
with a different (soft) keyword to make it easier for readers to recognize the difference from ternary expressions. How about when
? Also, I think this can be made to work for all collection types and function calls.
Therefore:
(1, (2, when cond), 4) # (1, (2,), 4) or (1, 4)
(1, (2, 3 when cond), 4) # (1, (2, 3), 4) or (1, 4)
(1, *(2, 3 when cond), 4) # (1, 2, 3, 4) or (1, 4)
[1, [2 when cond], 3, 4] # [1, 2, 3, 4] or [1, 3, 4]
{1, *{2, 3 when cond}, 4} # {1, 2, 3, 4} or {1, 4}
{1: x, {2: a, when cond}, 4: y} # {1: x, 2: a, 4: y} or {1: x, 4: y}
{1: x, **{2: a, 3: b when cond}, 4: y} # {1: x, 2: a, 3: b, 4: y} or {1: x, 4: y}
f(1, *(2, 3 when cond), 4) # f(1, 2, 3, 4) or f(1, 4)
f(1, *(2, 3 when cond), 4, **(a=b when cond2)) # f(1, 2, 3, 4, a=b) or f(1, 4)
How is that for:
- the parser?
- the human reader?
In summary:
- a display like
*(a, b, c, ... when cond)
is roughly equivalent to *((a, b, c, ...) if cond else ())
, and
- a display like
(a when cond)
is roughly equivalent to *((a,) if cond else ())
This illustrates the reduction in punctuation.