I'm trying to do this:
def Play(self, logic, board, id):
exec(logic)
l = Logic()
return l.Play(id, board)
logic
contains the code of the class Logic.
The errors is
NameError: global name 'Logic' is not defined
I'm trying to do this:
def Play(self, logic, board, id):
exec(logic)
l = Logic()
return l.Play(id, board)
logic
contains the code of the class Logic.
The errors is
NameError: global name 'Logic' is not defined
Because exec()
is now a function, you can no longer use it to set local names in Python functions.
In Python 2, where exec
is a statement, the compiler could detect its use and disable the normal local name optimisations in place for functions.
Execute your code into a new dictionary instead:
namespace = {}
exec(logic, namespace)
l = namespace['Logic']()
Demo:
>>> logic = '''\
... class Logic:
... def Play(self, id, board):
... return id, board
... '''
>>> def Play(logic, board, id):
... namespace = {}
... exec(logic, namespace)
... l = namespace['Logic']()
... return l.Play(id, board)
...
>>> Play(logic, 'foo_board', 'bar_id')
('bar_id', 'foo_board')