Call a function in main file from module using python

class, function, python

Solution

I would avoid creating circular dependencies and refactor your code such that foo3 is either in module, or another new module. For example (I cleaned things up a little bit as I went along to follow PEP8):

main.py

import module
example = module.Example()

def foo():
 module.foo2()

if __name__ == "__main__":
 foo()

module.py

import module3

class Example():
    def foo2(self):
        module3.foo3()

module3.py

 def foo3():
     print "here is the problem"

If you absolutely must keep the circular dependancy, then the best way to handle it would be to move the import in module.py to the end of the file as suggested on effbot. Again, I would avoid doing this at all cost.

class Example():
 def foo2(self):
  main.foo3()

import main

Problem

I am trying to make a python script that works so: I've got a main file that import another file, which is a class with functions inside it. The main file calls a function in the module, here it works all well, but when the def inside the module calls another def in the main again, I get an error. For example, in main.py I've got this ``` from module import * module = Example() def foo(): module.foo2() def foo3(): print "here is the problem" if(__name__ == "__main__"): foo() ``` In module.py I've got: ``` class Example(): def foo2(self): foo3() ``` foo2 is called perfectly, but when I try to call foo3() I get a NameError (global name 'foo3' is not defined). I know I should import it somehow but I don't know how to do it. Last thing: I am quite new to python so please explain good :-) Thanks

Original source