Python Forum

Full Version: exec() in class, NameError
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Pass 'self' as parameter.
def rysuj(self, frame, tuptus): 
    for bu in tuptus:
        def foo(self):
            exec('self.'+'y_coord')
        foo(self)
   
So why it works with 'print(self.x_coord)'?
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()
I get it :D Thank you
why would you have something like this in the class in the first place?
I tried to use similar way to pack buttons with command in function. I used closure instead.