MarAja
MarAja

Reputation: 1597

Cannot import name <MyClass> in Python

I try to import a class in python but I get some trouble probably because of cyclic import but I don't know how to solve my problem.

The loop that appears in my traceback (packageA contains three files: A, B and C):

**In main.py**    
from packageA import fileA
**In fileA.py:**
from packageA import fileB    <- 
**In fileB.py:**
from packageA import fileC
**In fileC.py:**
from fileB import ClassB      <-

I get:

ImportError: cannot import name ClassB

At first, I thought that I could delete "import ClassB" from fileC as the whole fileB had already been imported before. But if I try so I get another error which is:

NameError: global name 'ClassB' is not defined

Can someone help?

Upvotes: 0

Views: 189

Answers (1)

Kevin
Kevin

Reputation: 30151

This is a case of circular imports. fileB is importing fileC, which is importing fileB. The latter import is being satisfied with an empty, uninitialized module object.

In general, you do not want to use circular imports.

Upvotes: 2

Related Questions