简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM