Search code examples
pythonexec

Python exec() NameError: name 'self' is not defined


Why am I getting a NameError: name 'self' is not defined? This code is under a function in a class. main_root should be accessible anywhere in the class since it was initialized under __init__ as self.main_root = an element. The first parameter of the function is self too.

root_string = "self.main_root[0][1]"

globals()
code_locals = {'temp_string':""}

command_string = "temp_string = str(" + root_string + ".tag) + str(" + root_string + ".attrib)"
exec(command_string,globals(),code_locals)

If I set root_string = "main_root[0][1]" then I will get main_root is undefined. Even if I try to assign main_root = copy.deepcopy(self.main_root) beforehand.


Solution

  • if you need access self variable in the exec statement, you should pass the third parameter with locals(), not code_locals, in your sample.