我有一个非常简单的命名空间包(下面包含的内容,以及目录布局)。如果我尝试 import namespace_repro.module
,我收到以下错误:AttributeError: module 'namespace_repro' has no attribute 'module'
. 据我了解,我的包具有有效的布局,并且导入应该可以工作。有趣的是,该错误仅在 Python 3.6.8 中存在,并且在 Python 3.7 中导入成功。
如何重现问题?
我有一个名为 a 的目录import-error-repro
(setup.py
见下文),然后是一个嵌套目录 path src/namespace_repro/module
,其中包含三个文件__init__.py
、x.py
和y.py
. 他们的内容:
setup.py
from setuptools import find_namespace_packages, setup
setup(
name='namespace-repro',
version='0.1.0',
python_requires='>=3.6',
packages=find_namespace_packages('src'),
package_dir={'': 'src'},
zip_safe=False,
)
src/namespace_repro/module/__init__.py
:
from namespace_repro.module.x import x
src/namespace_repro/module/x.py
:
import namespace_repro.module.y as y
x = y.y
最后src/namespace_repro/module/y.py
:
y = True
我创建了一个全新的 Python 3.6 conda 环境conda create -n namespace6 python=3.6 ipython
,然后我激活它并将包安装为pip install -e ./import-error-repro
(注意-e
没关系,没有它问题是可重现的)。在那之后,我尝试 import namespace_repro.module
了ipython
(尽管在官方的 python 解释器中也发生了同样的情况)。结果是
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-1-bcae5a697dad> in <module>
----> 1 import namespace_repro.module
~/namespace-repro/src/namespace_repro/module/__init__.py in <module>
----> 1 from namespace_repro.module.x import x
~/namespace-repro/src/namespace_repro/module/x.py in <module>
----> 1 import namespace_repro.module.y as y
2
3 x = y.y
AttributeError: module 'namespace_repro' has no attribute 'module'
---------------------------------------------------------------------------
奇怪的是导入系统找到namespace_repro.module
了两次,第三次却失败了!
其他一些有趣的行为:
In [1]: import namespace_repro.module.y as y # This doesn't work.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-4035347ea59b> in <module>
----> 1 import namespace_repro.module.y as y
AttributeError: module 'namespace_repro' has no attribute 'module'
In [2]: import namespace_repro.module.y # But this one does! Why?
In [3]: dir(namespace_repro.module.y) # The error returns when we actually want to use the module.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-d89bcfd9e509> in <module>
----> 1 dir(namespace_repro.module.y)
AttributeError: module 'namespace_repro' has no attribute 'module'
In [4]: from namespace_repro.module.y import y # This works fine!
In [5]: y
Out[5]: True
目录布局
. import-error-repro
+-- setup.py
+-- src
| +-- namespace_repro
| | +-- module
| | | +-- __init__.py
| | | +-- x.py
| | | +-- y.py