0

The following code:

exec(str(newName) + " = Leagues('"+str(name)+"','" + str(ldata[2]) + "'," + str(teams) + "," + str(len(teams)) + "," + str(ldata[3]) + "," + str(ldata[4]) + "," + str(ldata[5]) +")")

Runs without a syntax error however does not carry out its purpose (define an object of a class, "Leagues").

The code operates in a loop so it essentially looks like this (without the array indexing and breaks in the speech marks):

exec("EnglishDivision1 = Leagues('English Division 1','England',[#an array],20,4,3,3)")

The code above runs but does not actually create an object. However, when I enter this exact code without the exec command, it works just fine and an object is created. Anyone know what's going on?

webprogrammer
  • 2,393
  • 3
  • 21
  • 27
Xaeol
  • 101
  • 6
  • 1
    I think this is a namespace issue with `exec`. Note that `exec` is *very* different between Python 2 and Python 3, but from your post I assume you're using Python 3. I'm including a previous answer that may help (look at Martijn's answer). – Tom Karzes Feb 29 '20 at 20:47
  • Does this answer your question? [Behavior of exec function in Python 2 and Python 3](https://stackoverflow.com/questions/15086040/behavior-of-exec-function-in-python-2-and-python-3) – Tom Karzes Feb 29 '20 at 20:47
  • By the way, a better way to do this is to keep your values in a `dict`, which will allow you to avoid the use of `exec` altogether. – Tom Karzes Feb 29 '20 at 20:50
  • The code works while not in a function, why does this happen? Is this a namespace error? – Xaeol Feb 29 '20 at 21:05
  • When not in a function, it uses the global namespace for the assignment. – Tom Karzes Feb 29 '20 at 21:06

0 Answers0