Conditional collection literals

That’s exactly how I’ve been relunctantly doing it myself. The proposed syntax is both more readable to me and more efficient.

I think we can remedy both concerns with a leading keyword and a forced indented block instead:

{
    'a': 1,
    if bar is not None:
        'b': 2,
        'c': 3,
    'd': 4,
}

This allows insertion of multiple items on one condition without the need for an unpacking operator too, although unpacking can still be allowed:

[
    '-l',
    if bar is not None:
        '--',
        *map(str, numbers),
]

The only downside I can think of is that an implementation will require a bigger change to the parser because currently there’s no indentation enforcement whatsoever inside brackets.

1 Like