3

I have a file called main.py and a file called classes.py

main.py contains the application and what's happening while class.py contains some classes.

main.py has the following code

main.py

import classes

def addItem(text):
    print text

myClass = classes.ExampleClass()

And then we have classes.py

classes.py

class ExampleClass (object):
    def __init__(self):
        addItem('bob')

Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?

Thanks in advance

Teifion
  • 108,121
  • 75
  • 161
  • 195

4 Answers4

9

I couldn't answer this any better than this post by Alex Martelli. Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules...

If you have two modules A and B which depend on each other, the easiest way is to isolate a part of the code that they both depend on into a third module C, and have both of them import C.

dF.
  • 74,139
  • 30
  • 130
  • 136
  • I assume you mean [this post by Alex Martelli](http://mail.python.org/pipermail/python-list/2000-December/059926.html)? – balpha Apr 05 '10 at 09:00
  • @balpha and dF: I get the feeling that pipermail periodically changes the links (unfortunately). I don't know why they do this. I also don't know who uses permanent links. Maybe Google (http://groups.google.com/group/comp.lang.python/msg/9f93de7370c53d21)? – John Y Apr 05 '10 at 23:30
3

The suggestions to refactor are good ones. If you have to leave the files as they are, then you can edit main.py to make sure that nothing is executed simply by importing the file, then import main in the function that needs it:

class ExampleClass (object):
    def __init__(self):
        import main
        main.addItem('bob')

This avoids the circular imports, but isn't as nice as refactoring in the first place...

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

I would suggest putting common functions either in classes.py, or probably even better in a third module, perhaps utils.py.

Ali Afshar
  • 40,967
  • 12
  • 95
  • 109
1

All your executable code should be inside a if __name__ == "__main__" . This will prevent it from being execucted when imported as a module. In main.py

if __name__=="__main__":
    myClass = classes.ExampleClass()

However, as dF states, it is probably better to refactor at this stage than to try to resolve cyclic dependencies.

codelogic
  • 71,764
  • 9
  • 59
  • 54