我在使用 Python 单元测试时遇到了一个奇怪的错误。我的项目中有两个文件夹:
project
code
__init__.py (empty)
app.py (defines my App class)
test
test.py (contains my unit tests)
test.py 是:
import os, sys, unittest
sys.path.insert(1, os.path.join(sys.path[0],'..'))
from code.app import App
class test_func1(unittest.TestCase):
...
当我运行 test.py 时,我收到消息:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "...test.py, line 5, in <module>
from code.app import App
ImportError: No module named 'code.app': 'code' is not a package
在确认 __init__.py
存在并敲了一会儿脑袋之后,我一时兴起将应用程序目录的名称从 code 更改为 prog:
import os, sys, unittest
sys.path.insert(1, os.path.join(sys.path[0],'..'))
from prog.app import App
...一切突然都好了。 Unittest 正确导入了我的应用程序并运行了测试。
我搜索了 https://docs.python.org/3.5/reference/lexical_analysis.html#keywords和 https://docs.python.org/3/reference/import.html#path-entry-finders并且看不到任何表明 code
是非法目录名称的迹象。这将记录在哪里,还有哪些其他目录名称被保留?
系统:python 3.4.3 [MSC v1600 32 位] on win32, Windows 7
最佳答案
code
不是保留的,但它是 已经在标准库中定义,它是常规模块而不是包。要从您的包中导入,您应该使用相对导入。
from .code.app import App
关于python - 保留的 Python 模块/包名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066242/