简体   繁体   中英

How do I deal with error while importing in Python

I have got 2 modules which tend to import each other because they will be using each other in classes. I found in this link which tells to use try/except statement along with imports to deal with circular imports, but still I am getting KeyError instead.

The name of module is brand.py which contains the following code:

try:
    from erp.common.models.productwithspecs import ProductWithSpec, ProductWithSpecSchema
except ImportError:
    import sys
    ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']

but I get the below error:

File "/home/arsalan/python_practise/MY_WORK_FILES/React_works/React_Container_Mount/backend/erp/common/models/brand.py", line 13, in <module>
    ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']
KeyError: 'erp.common.models.productwithspecs.ProductWithSpec'` Can anybody point out the mistake

I have got 2 modules which tend to import each other because they will be using each other in classes

Then you have a design issue, and the proper solution is not hack around it but to solve this design issue. Having circular dependencies between modules is a big no no whatever the language, even when it's technically possible.

You have three possible solutions here, depending on the concrete case: extracting common deps to a third module, regrouping both modules in one, and using dependency injection. But by all means avoid the temptation to resort to ugly hacks that will cause various issues later on (been here, done that :-/ , now I know better).

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