Why does eval()
of expressions with list comprehension work fine, if done outside a function, but cease to work under all circumstances, as soon as I run the same commands inside a function? E. g., why does
fruit = ['apple', 'banana', 'cherry']
meat = ['chicken', 'beef', 'steak']
s = eval("[meat[k] for k, _ in enumerate(fruit)]")
print(s)
work, but not
def main():
fruit = ['apple', 'banana', 'cherry']
meat = ['chicken', 'beef', 'steak']
s = eval("[meat[k] for k, _ in enumerate(fruit)]")
print(s)
return
main();
?
My example is a little contrived. But it's a minimal example nonetheless. In my actual applications I use more complicated expressions, but the above demonstrates the point at which eval()
breaks down. I've also tried using eval(..., globals(), locals())
, eval(..., None, locals())
, etc., But nothing seems to help.