Checking if any item in one set is in another set using a single comprehension possible?

49 Views Asked by At

I have the following check in my unit test:

assert any(pass1_task in (task for task in all_downstream_task_for_dl_task) for pass1_task in {'first_pass', 'first_cpp_pass'}), 'the test failed unexpectedly'

The unit test above fails, however, I am expecting it to pass.

all_downstream_task_for_dl_task is a set with 2 items:

all_downstream_task_for_dl_task = {'cbbo_snowflake_copy_XAMS', 'first_cpp_pass.euronext3-equities_nl_A_3'}

In reality the list is much longer, but for simplicity let's say it contains the above two.

Is my list comprehension not doing what I expect it to?

I would expect the unit test to pass, since the second item in all_downstream_task_for_dl_task contains first_cpp_pass

1

There are 1 best solutions below

1
balintd On BEST ANSWER

I generally avoid comprehensions when its line overflows 79 characters, not only because of PEP 8, but also because they lose their main goal of simplifying code. This is what you want to achieve, if I get it right:

is_in_task = []
for pass1_task in {'first_pass', 'first_cpp_pass'}:
    for task in all_downstream_task_for_dl_task:
        is_in_task.append(pass1_task in task)

assert any(is_in_task), 'the test failed unexpectedly'

And with comprehension:

assert any(pass1_task in task for task in all_downstream_task_for_dl_task for pass1_task in {'first_pass', 'first_cpp_pass'}), 'the test failed unexpectedly'

So mainly, you just have to remove the parentheses from the inner for loop because with parentheses, your code checks whether pass1_task is in the generator that is defined between the parentheses, which evaluates to False.