为何无法将Python模块命名为‘array’?运行pytest时遇导入错误
问题分析与解决
问题场景
目录结构如下:
app/ └── array/ ├── test/ │ ├── __init__.py │ └── test_array.py ├── __init__.py └── functions.py
在app目录下运行pytest时,出现错误:
ERROR collecting array/test/test_array.py _______________________________________ ImportError while importing test module '/path/to/app/array/test/test_array.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) E ModuleNotFoundError: No module named 'array.test'; 'array' is not a package
将模块重命名为arrays后可正常运行,疑惑命名为array的问题所在。
原因
Python标准库中内置了同名的array模块,当pytest尝试导入你的array.test模块时,Python的导入优先级会先加载标准库的array模块,而非你项目中的array包。标准库的array是单一模块(非包结构),自然不存在array.test子模块,因此抛出ModuleNotFoundError。
验证方法
你可以在Python交互环境中执行以下命令,确认导入的array来源:
import array print(array.__file__)
输出路径会指向Python标准库目录下的array.py,而非你项目中的array文件夹。
解决方案
- 避免使用与Python标准库模块同名的包/模块名称,比如将
array重命名为arrays、my_array等; - 若必须保留
array名称,可通过修改Python的sys.path将项目目录优先级提到标准库之前,但这种方式容易引发其他导入冲突,不推荐。
内容的提问来源于stack exchange,提问作者Abhijit Sarkar
相关产品推荐
相关产品推荐

