Circular Import?

C

Chris S.

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?
 
B

Benjamin Niemann

Chris said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top