Search code examples
pythonclassdefinitionforward-declaration

Circular dependencies python for functions in same file


I have code structure something like this:-

def send_message(msg):
    print msg + "\n"
    x.new_message("You",msg)


class GUI(Frame):

def createWidgets(self):
    self.input.bind('<Key-Return>',self.send)

def send(self, event):
    send_message(self.contents.get())
    self.contents.set("")
def new_message(self,sender, msg):
    line = sender+": "+msg+"\n"
    self.chat.contents.set(self.chat.contents.get()+line)

def __init__(self):
    self.createWidgets()

x = GUI()

As you can see, this has some circular dependancies. Function send_message requires instance x as well as new_message method of GUI. GUI definition needs send_message. Thus it is not possible to satisfy all the constraints. What to do?


Solution

  • In the complete code you showed in die comments we can see that you call self.mainloop() in GUI.__init__. This will start the event handling of the gui and will probably not terminate until the program in finished. Only then the assignment x = GUI() will finish and x will be available.

    To circumvent this you have multiple options. Generally doing an endless loop in __init__ is probably a bad idea. Instead call mainloop() after the GUI is instantiated.

    def __init__(self):
        # only do init
    
    x = GUI()
    x.mainloop()
    

    As jasonharper said in python variables in functions are only looked up when you execute that function, not when defining them. Thus circular dependencies in runtime are most of the time not a problem in python.