ImportError:无法导入名称-两个具有相同名称的模块

时间:2019-12-07 02:15:55

标签: python python-3.x python-import importerror

我不明白为什么会收到ImportError。据我所知,没有循环依赖。这与我有两个名为“ constants.py”的文件有关吗?我该如何解决?

下面是我的目录结构(不相关的文件和文件夹已删除):

<top-level directory>
├───spam
│   │   constants.py
│   │   spam.py
│   └───__pycache__
│           constants.cpython-37.pyc
│           spam.cpython-37.pyc
│
├───project_metrics
│   │   main.py
│   ├───data
│   ├───spam_x_ham
│   │   │   constants.py
│   │   │   spam_x_ham.py
│   │   │
│   │   └───__pycache__
│   │           constants.cpython-37.pyc

在spam / spam.py中:

from constants import A, B, C

spam / constants.py定义了变量A,B和C。

在project_metrics / spam_x_ham / spam_x_ham.py中:

import sys
sys.path.insert(0, <path to top-level directory>)

from constants import X, Y, Z
from spam.spam import foo           # Error raised because of this line

project_metrics / spam_x_ham / constants.py定义了变量X,Y和Z。

当我运行project_metrics / spam_x_ham / spam_x_ham.py时,出现以下错误:

Traceback (most recent call last):
  File "<top-level directory>/project_metrics/spam_x_ham/spam_x_ham.py", line 19, in <module>
    from spam.spam import foo
  File "<top-level directory>\spam\spam.py", line 8, in <module>
    from constants import A
ImportError: cannot import name 'A' from 'constants' (<top-level directory>\project_metrics\spam_x_ham\constants.py)

我正在使用python版本3.7.1。

0 个答案:

没有答案