Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

exec

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.

like image 966
user1179317 Avatar asked Mar 06 '26 02:03

user1179317


1 Answers

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

like image 167
Hooting Avatar answered Mar 07 '26 15:03

Hooting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!