How do I deal with error while importing in Python

本秂侑毒 提交于 2021-01-29 12:01:19

问题


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

回答1:


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).



来源:https://stackoverflow.com/questions/61075955/how-do-i-deal-with-error-while-importing-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!