1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
RiKr2
  • 13
  • 3
  • 1
    @BhargavRao: actually, that post doesn't come close in explaining what happens here. See [Behaviour of exec function in Python 2 and Python 3](http://stackoverflow.com/q/15086040) instead. – Martijn Pieters Jan 12 '15 at 14:19
  • @MartijnPieters Yeah, the other is better. Thanks – Bhargav Rao Jan 12 '15 at 14:21

1 Answers1

3

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343