3

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.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
user1179317
  • 2,693
  • 3
  • 34
  • 62
  • Does this answer your question? [How does exec work with locals?](https://stackoverflow.com/questions/1463306/how-does-exec-work-with-locals) – Llamax Aug 31 '21 at 16:43

2 Answers2

4

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

Hooting
  • 1,681
  • 11
  • 20
0

it should be

root_string =self.main_root[0][1]

or if you want it as string,do it as

root_string = str(self.root[0][1])

you have to convert a variable to type(string,int,etc) you want you cannot initialize it as " self.main_root[0][1]"

aroy
  • 452
  • 2
  • 10
  • Im using the exec() which uses a string. Also the address, in this example " [0][1]" is from another function. How would you propose your solution if the address [0][1] came to you as a string – user1179317 May 11 '16 at 04:29