在 Python 中导入时如何处理错误
How do I deal with error while importing in Python
我有 2 个模块,它们倾向于相互导入,因为它们将在 类 中相互使用。我在 this link 中找到它告诉我使用 try/except
语句和导入来处理循环导入,但我仍然得到 KeyError
。
模块名称为brand.py
,包含以下代码:
try:
from erp.common.models.productwithspecs import ProductWithSpec, ProductWithSpecSchema
except ImportError:
import sys
ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']
但我收到以下错误:
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
然后你有一个设计问题,正确的解决方案不是绕过它而是解决这个设计问题。无论哪种语言,模块之间的循环依赖都是一个很大的禁忌,即使它在技术上是可行的。
根据具体情况,您在这里有三种可能的解决方案:将公共依赖提取到第三个模块,将两个模块重新组合为一个模块,并使用依赖注入。但一定要避免诉诸丑陋黑客的诱惑,这些黑客 会在以后 导致各种问题(在这里,做过 :-/
,现在我知道得更多了)。
我有 2 个模块,它们倾向于相互导入,因为它们将在 类 中相互使用。我在 this link 中找到它告诉我使用 try/except
语句和导入来处理循环导入,但我仍然得到 KeyError
。
模块名称为brand.py
,包含以下代码:
try:
from erp.common.models.productwithspecs import ProductWithSpec, ProductWithSpecSchema
except ImportError:
import sys
ProductWithSpec = sys.modules[__package__ + '.productwithspecs.ProductWithSpec']
但我收到以下错误:
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
然后你有一个设计问题,正确的解决方案不是绕过它而是解决这个设计问题。无论哪种语言,模块之间的循环依赖都是一个很大的禁忌,即使它在技术上是可行的。
根据具体情况,您在这里有三种可能的解决方案:将公共依赖提取到第三个模块,将两个模块重新组合为一个模块,并使用依赖注入。但一定要避免诉诸丑陋黑客的诱惑,这些黑客 会在以后 导致各种问题(在这里,做过 :-/
,现在我知道得更多了)。