Python Forum
exec() in class, NameError - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: exec() in class, NameError (/thread-25537.html)



exec() in class, NameError - niski1996 - Apr-02-2020

Hi. I've got a problem with exec() function in my class. If code is like:
    def rysuj(self, frame, tuptus):
        for bu in tuptus:
            def foo():
                print(self.x_coord)
                exec('self.'+'y_coord')
            foo()
everything is fine, but if i delate print:
    def rysuj(self, frame, tuptus): 
        for bu in tuptus:
            def foo():
                exec('self.'+'y_coord')
            foo()
gives me an error
Error:
"C:\Users\karol\anaconda3\envs\porjekt ostateczny\python.exe" "C:\Users\karol\PycharmProjects\porjekt ostateczny\main_menu_by_tkinter_2.py" Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\karol\anaconda3\envs\porjekt ostateczny\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "C:\Users\karol\PycharmProjects\porjekt ostateczny\main_menu_by_tkinter_2.py", line 152, in <lambda> command=lambda: self.rysuj(self.ctr_left,przyciski_rysuj), File "C:\Users\karol\PycharmProjects\porjekt ostateczny\main_menu_by_tkinter_2.py", line 177, in rysuj foo() File "C:\Users\karol\PycharmProjects\porjekt ostateczny\main_menu_by_tkinter_2.py", line 176, in foo exec('self.'+'y_coord') File "<string>", line 1, in <module> NameError: name 'self' is not defined
does anybody know why?


RE: exec() in class, NameError - Mateusz - Apr-02-2020

Pass 'self' as parameter.
def rysuj(self, frame, tuptus): 
    for bu in tuptus:
        def foo(self):
            exec('self.'+'y_coord')
        foo(self)
   



RE: exec() in class, NameError - niski1996 - Apr-02-2020

So why it works with 'print(self.x_coord)'?


RE: exec() in class, NameError - Mateusz - Apr-02-2020

Because print function set te locals variables. See below:
def rysuj(self, frame, tuptus): 
    for bu in tuptus:
        def foo():
            print(locals())
            exec('self.'+'y_coord')
        foo()
and
def rysuj(self, frame, tuptus): 
    for bu in tuptus:
        def foo():
            print(self)
            print(locals())
            exec('self.'+'y_coord')
        foo()



RE: exec() in class, NameError - niski1996 - Apr-02-2020

I get it :D Thank you


RE: exec() in class, NameError - buran - Apr-02-2020

why would you have something like this in the class in the first place?


RE: exec() in class, NameError - niski1996 - Apr-20-2020

I tried to use similar way to pack buttons with command in function. I used closure instead.