Circular Import?

Benjamin Niemann pink at odahoda.de
Sat Aug 28 11:38:31 CEST 2004


Chris S. wrote:

> Consider the sample case:
> 
> ## a.py
> import d
> import b
> b.App()
> 
> ## b.py
> from c import C
> B = 'B'
> class App(object):pass
> 
> ## c.py
> from d import D
> class C(object):pass
> 
> ## d.py
> from b import B
> D = 'D'
> 
> Executing a.py will return:
> Traceback (most recent call last):
>   File "a.py", line 1, in ?
>     import d
>   File "d.py", line 1, in ?
>     from b import B
>   File "b.py", line 1, in ?
>     from c import C
>   File "c.py", line 1, in ?
>     from d import D
> ImportError: cannot import name D
> 
> I'm assuming this is the result of the circular imports. This isn't a 
> bug, right? Is there any way around it?
Yep, circular imports only cause problems. Workarounds:
- design your application not to use circular dependencies, as these are 
usually a sign for bad design
- use late imports:

## foo.py
class A:
   def a():
     import bar # instead of importing at the beginning of foo
     bar.B()

## bar.py
import foo

def B():
   pass

class C(A):
   pass






More information about the Python-list mailing list