What is the best way to handle the import loop in Python?

In our projects, we have levels of "control" with the following modules: "grid", "grid", "combo", etc. The grid module imports the gridcell module, because the grid consists of cells, and any cell can contain combos inside it. Therefore, initially we start using the expressions "from ... import ..." inside these classes as follows:

#grid.py from controls.gridcell import cell #gridcell.py from controls.combo import combo 

But that was fine until we started using the grid as combo content. As soon as we started to do this, we needed to add the expression “from grid import grid” to “combo.py”. After that, we get an import exception:

 from controls.gridcell import gridcell ImportError: Cannot import name gridcell 

Edition:

I also tried "import ... as ..." and got the following error:

 import controls.gridcell as gridcell AttributeError: 'module' object has no attribute 'gridcell' 

I read several articles and all I found on how to solve this problem is to use the "import" operator without, for example:

 #grid.py import controls.gridcell #gridcell.py import controls.combo #combo.py import controls.grid 

But this forces us to use full names, such as "controls.gridcell.cell", "controls.combo.combo", "controls.grid.grid", etc.

So my question is: is there any other way to do this (so that it is available to use shorter names), or is this the only way to solve this problem?

Sorry if I missed something.

Thanx for everyone

+4
source share
2 answers
 import controls.gridcell as gridcell 

etc .. etc etc.

+9
source

You can also move imports to functions.

 def foo(): from controls.gridcell import cell from controls.combo import combo 

if you have an init() function, this might be convenient.

+2
source

All Articles