Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have the following check in my unit test:

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 above fails the unit test, when I am expecting it to pass.

all_downstream_task_for_dl_task is a list with 2 items:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {'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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading