Home > Software engineering >  Using ``exec()`` in a comprehension list
Using ``exec()`` in a comprehension list

Time:12-20

I have a script that can be run independently but sometimes will be externally invoked with parameters meant to override the ones defined in the script. I got it working using exec() (the safety of this approach is not the point here) but I don't understand why it works in a for loop and not in a comprehension list.

foo = 1
bar = 2

externally_given = ['foo=10', 'bar=20']
for ext in externally_given:
    exec(ext)

print('Exec in for loop ->', foo, bar)

externally_given = ['foo=30', 'bar=40']
[exec(ext) for ext in externally_given]

print('Exec in comprehension list ->', foo, bar)

Output:

Exec in for loop -> 10 20
Exec in comprehension list -> 10 20

EDIT: Python version 3.10

CodePudding user response:

To update global variables, let exec() have access to them by passing globals() as the second parameter:

[exec(ext,globals()) for ext in externally_given]
# [None, None]
foo
# 10
bar
# 20

(Subject to all the good comments to the original post.)

  • Related