Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to deal with import cycle in Python?

In our projects we have level 'controls' with the following modules: 'grid', 'gridcell', 'combo' and etc. Grid module imports gridcell module since grid consists of cells, while any cell can contain combo inside it. So initially we starting to use 'from ... import ...' statements inside these classes the following way:

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

But this was ok until we start using grid as a combo content. As soon as we start doing this we were required to add 'from grid import grid' statement into the 'combo.py'. After doing this we get an import exception:

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

EDITED:

I have tried also 'import ... as ...' and get the following error:

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

I have read several articles and all that i have found about how to solve this is to use 'import' statement without from, e.g:

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

But this leads us to use full names like 'controls.gridcell.cell', 'controls.combo.combo', 'controls.grid.grid' and so on.

So my question is - Is there any other way how to do this(so it would be available to use shorter names) or this is the only way of how to resolve this issue?

Sorry if i miss something

Thanx to all

like image 423
Artsiom Rudzenka Avatar asked Jun 16 '11 16:06

Artsiom Rudzenka


2 Answers

import controls.gridcell as gridcell

etc. etc. etc. etc.

like image 184
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 22:09

Ignacio Vazquez-Abrams


you can also move the imports into the functions.

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

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

like image 45
Guy Avatar answered Oct 01 '22 00:10

Guy