Python exec with a function chain producing NameError

From the documentation:

If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

And class definitions do not create enclosing scope, note, this is why you cannot call a method from another method without using self. So just pass the globals() dictionary. Or pass two of the same dict’s to both arguments.

In [4]: def run_code():
   ...:     code = """
   ...: def foo():
   ...:   print('foo')
   ...:   return 1
   ...: def bar():
   ...:   print('bar calls foo')
   ...:   return 1 + foo()
   ...: result = bar()
   ...: """
   ...:     namespace = {}
   ...:     exec(code, namespace)
   ...:     print('Result: {}'.format(namespace['result']))

In [5]: run_code()
bar calls foo
Result: 2

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top