Hello everyone ![]()
I would like to propose a new syntax feature and am here to gather feedback before writing a PEP about it.
I regularly find myself in a situation where I would like to write a collection literal in which some elements are conditional.
For simplicity, I will focus on lists, but the same idea holds for dicts, sets and tuples.
(I included some examples at the end of this post.)
It would look like this:
my_list = [
elem_1,
elem_2 if condition,
elem_3,
]
where elem_2 is only included in my_list if condition evaluates to True.
Do not confuse this with if-expressions, which will always evaluate to something.
It relates well to comprehensions, where we have a filtering if, e.g.:
[x for x in xs if x > 5]
and takes the form of the guards from cases, which are defined as:
guard ::= "if" named_expression
My best guess at how the same functionality could be achieved with the existing syntax is by constructing the list with ifs-blocks:
my_list = [elem_1]
if condition:
my_list.append(elem_2)
my_list.append(elem_3)
This approach gets worse the more complex such a literal becomes.
I believe that my example syntax above fits well into python, closes a logical gap and allows for much cleaner code, compared to any other currently valid implementation than can do the same.
Here are the examples for the other collection types:
my_dict = {
'a': elem_1,
'b': elem_2 if condition,
'c': elem_3,
}
my_set = {
elem_1,
elem_2 if condition,
elem_3,
}
my_tuple = (
'a': elem_1,
'b': elem_2 if condition,
'c': elem_3,
)
I am looking forward to reading your feedback ![]()