0

I have run the below code:

def test(yymm):
    exec("test_var_" + yymm + " = 'abc'")
    print(test_var_1912)

test('1912')

My expected output is to assign the variable 'test_var_1912' and print out string "abc". However, Python prompt the below error message:

NameError: name 'test_var_1912' is not defined

Could anyone please help to solve my question?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You cannot use `exec` or `eval` to assign to the local namespace. But you never have to. What are you *actually trying to do*? – juanpa.arrivillaga Jan 09 '20 at 03:59
  • use dictionary to keep it - `test_var = dict()`, `test_var["1912"] = 'abc'` - `print(test_var["1912"])` – furas Jan 09 '20 at 04:03
  • @furas that will work, but again, *almost certainly* there is a way to accomplish it without `exec` that will be more elegant and less brittle. – juanpa.arrivillaga Jan 09 '20 at 04:09
  • @furas You can keep the dynamic variable in special `globals()` dict like this `exec("test_var_" + yymm + " = 'abc'", globals())` – Thành Chung Bùi Jan 09 '20 at 04:12
  • 1
    @ThànhChungBùi all languages have dictionary for this and using `global` and `exec` is not good idea. – furas Jan 09 '20 at 04:15

0 Answers0