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

Problem with converting function arguments to list

I have the following code:

>>> def test(a,b,c,d):
...     print([x in [a,b,c,d] for x in [1,]])
...     print([x in list(locals().values()) for x in [1,]])

>>> test(1, 2, 3, 4)
[True]
[True]

>>> test(2, 2, 3, 4)
[False]
[True]

This implementation might seem a bit weird, but the example stems from a bigger project where there are many function arguments.

For the first call of the function, everything behaves as expected with the same result for both statements. For the second call, however, the behaviour seems very strange to me. Can anybody explain what’s going on here?

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

Thanks!

>Solution :

locals() refers to the local values of the list comprehension.

Consider:

def test(a,b,c,d):
    print([x in [a,b,c,d] for x in [1,]])
    print([(x in list(locals().values()) and not print(locals())) for x in [1,]])

Explanation

not print(locals()) is not None which evaluates to True, so and not print(locals()) does not change the result of the boolean expression.

Output:

>>> test(2, 2, 3, 4)
[False]
{'.0': <tuple_iterator object at 0x000001A4D070CDC0>, 'x': 1}
[True]

So you’re getting [True] from the second print because of course the loop variable x is in the local scope.

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