Calling From A Parent File In Python
Solution 1:
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.
Solution 2:
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:
classExampleClass (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...
Solution 3:
I would suggest putting common functions either in classes.py, or probably even better in a third module, perhaps utils.py.
Solution 4:
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.
Post a Comment for "Calling From A Parent File In Python"