-1

I'm porting some Python 2 code to Python 3

I know this code snippet is bad practice, but I am looking for a way replace the exec() calls. I basically get "None" back, as predicted by the migration documents. I tried eval() but I get syntax error messages.

What are the alternatives dynamically generating variable names?

value = "test"
for field in ['overviewSynopsis', 'callsToAction_productLevel']:
    exec(field +'_value = ""')
    exec(field +'_value = value')
    print(exec(field + "_value"))
Steve
  • 3,127
  • 14
  • 56
  • 96
  • 3
    Is there any reason you won't use a dictionary? – Juan C Dec 10 '19 at 21:18
  • What do you expect to get back? Assignment statements aren't expressions, they don't evaluate to a value. Don't do this to begin with, use a *container* like a dict or a list – juanpa.arrivillaga Dec 10 '19 at 21:19
  • @juanpa.arrivillaga `exec` was changed from a statement to an expression. obviously they want it to bind a name, like it used to in py2. – wim Dec 10 '19 at 21:19
  • It is very difficult to do correctly. See [How to convert this Python 2.7 code to Python 3?](https://stackoverflow.com/q/57595351/674039) for example. Better to refactor the code to use dictionaries instead. – wim Dec 10 '19 at 21:21
  • @wim sure, exec is a function now that always returns `None`, my point is *that assignment statements aren't expressions*, so what would they expect `exec` to return here anyway? – juanpa.arrivillaga Dec 10 '19 at 21:22
  • 2
    For that 3rd exec, I assume they probably meant `eval`. – wim Dec 10 '19 at 21:23
  • 1
    It sounds like they want `exec` to return whatever is inside it. What I think OP wants is `eval`. However, both should be avoided and OP should use a dictionary instead – SyntaxVoid Dec 10 '19 at 21:23

1 Answers1

0

Use a dictionary instead. You can map a key name to a value.

mipadi
  • 398,885
  • 90
  • 523
  • 479