exec()
from inside a function gives a different output, even I pass all the parameter needed to that function. Consider this code:
def list_filter(expr,datalist,includelist) :
exec(expr)
print outlist
datalist=['try to kill me','black image']
includelist=['me']
expr="outlist = [i for i in datalist if all(j in i for j in includelist) ]"
exec(expr)
print outlist
list_filter(expr,datalist,includelist)
I have checked the similar case here : How does exec work with locals?
But this is a different error, where I'm using version 2.7.13 and I check under general condition, the exec()
normally has no error at all. I found this problem shows up when there's a 'nested loop' inside list comprehension statement, such as using all()
or any()
. As in this case , if I remove the if condition
from the list comprehension (make it to be expr = "outlist = [i for i in datalist ]"
) then I will get the correct output as usual.
Any idea why?