Using “exec()“ in a comprehension list

Question:

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

Asked By: Martí

||

Answers:

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.)

Answered By: DYZ
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.