Reputation: 309
Another question about modules importing each other I know :(
Basically, I have a file main.py containing this :
class Main :
@staticmethod
def newMouton(mouton, i, j) :
listMoutons.append(mouton)
listMoutons.append(canvas.create_image(i * coteCarre, j * coteCarre + yMargin, img = imageMouton))
@staticmethod
def delMouton(mouton) :
moutonIndex = listMoutons.index(mouton)
canvas.delete(listMoutons[moutonIndex + 1]) #en ajoutant 1, on retrouve l'obj canvas image à supprimer
listMoutons.remove(mouton)
del listMoutons[moutonIndex:(moutonIndex + 2)]
from random import randint
from simulation import Simulation
#doing some other stuff such as creating the canvas variable and creating a Simulation instance
And I have another file simulation.py :
from main import Main
class Simulation:
def __init__(self) : self._moutons = []
def moutonMort(self, mouton) :
self._moutons.remove(mouton)
pos = mouton.getPosition()
Main.delMouton(mouton)
del mouton
When I try to run main.py Python runs into an error and it basically says that the problem is coming from the fact that I am trying to import Simulation in Main but then I import Main in Simulation.
To understand a bit more about how import work I read this question and I am quite lost : when I run main.py what should happen is :
But it turns out that's not the case : when Python reads the import Main statement in the simulation file, it tries to run again the content in the main file, although it is already imported
I hope my explanation is clear
Upvotes: 1
Views: 104
Reputation: 2014
In simulation.py, your intent is to import only Main this is via the main module and the main module is not yet ready because it is still importing simulation. This is a circular reference situation. It is a common problem when starting out with Python. You need to arrange your module references into a tree like structure, there should be no back referencing.
Don't feel this is an inconvenient Pyton constraint; it is forcing you to write good code and avoiding you getting into more trouble further down the line. basically every class or function should be concerned with only one thing and coupling to other classes and fuctions should be minimised.
It appears you are spreading a concern (simulation) across two modules. The name Main for a class is not descriptive and I am not sure what it represents. But I suggest the main module has a dependency on Simulation and Simulation should implement Mouton methods directly or via a Mouton class.
Upvotes: 1