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?
Thanks!
CodePudding user response:
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.