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

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I assume you mean this post by Alex Martelli?
@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 (groups.google.com/group/comp.lang.python/msg/9f93de7370c53d21)?
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...

Comments

1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.