【发布时间】:2016-03-17 16:21:41
【问题描述】:
我在使用 Python unittest 时遇到了一个奇怪的错误。我的项目中有两个文件夹:
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 bit] on win32, Windows 7
【问题讨论】:
-
code不是保留名称,但在标准库中有一个 existing module 以该名称命名,因此将模块命名为code是个坏主意,就像将列表命名为 @ 987654333@。我希望您的模块能够使用您提供的信息来隐藏内置模块,但有许多可能性会使它走另一种方式。 -
如果我错了,请纠正我,但你应该这样做
from code import app,这取决于你在__init__.py中定义的内容。如果app在__init__.py中定义,也许你可以做from code.app ...,如果是这样,请忽略我的评论。 -
@Torxed,在脚本中使用
from prog import app然后使用合格的app.App更为明确。这不需要__init__.py中的任何内容,但只有在您想要导入和使用两个都定义了App的不同模块时才需要。 -
注意,我什至不会遇到这个问题,但事实上我遇到了用户定义的异常问题,需要想出一个小例子来发布到 SO。包含异常的小例子工作正常(只要它有一个不冲突的包名),所以现在它回到了主要问题。
标签: python unit-testing python-3.x