保留的Python模块/包名称是什么?
在使用Python unittest时,我遇到了一个奇怪的错误。我的项目中有两个文件夹:保留的Python模块/包名称是什么?,python,unit-testing,python-3.x,Python,Unit Testing,Python 3.x,在使用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.pa
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
。。。突然一切都好了。Unittest正确导入了我的应用程序并运行了测试
我搜索了一遍,没有发现任何迹象表明code
是非法的目录名。这将记录在哪里,保留哪些其他目录名
系统:win32、Windows 7上的python 3.4.3[MSC v1600 32位]未保留,但已在标准库中定义,它是常规模块而不是包。要从包中导入,应使用相对导入
from .code.app import App
code
不是保留名称,但标准库中有一个名称,因此给模块命名code
是个坏主意,就像给列表命名list
一样。我希望您的模块使用您提供的信息来隐藏内置模块,但有许多可能会使其发生相反的情况。如果我错了,请纠正我,但您应该从代码导入应用程序执行,具体取决于您在\uu init\uuuuy.py
中定义的内容。如果中定义了app
,那么您可以从code.app执行。
,如果是这样,请忽略我的评论。@torx,从prog import app执行,然后在脚本中使用合格的app.app
,这更为明确。这并不需要\uuuu init\uuuuuuy.py
中的任何内容,但只有当您想要导入和使用两个不同的模块,这两个模块都定义了应用程序
时才有必要。注意,如果不是因为我在用户定义的异常方面遇到问题,我甚至不会遇到这个问题,并且需要拿出一个小示例来发布。包含异常的小示例运行良好(只要它有一个不冲突的包名),因此现在回到主要问题。根据PEP-0404问题,您应该是正确的。但是当我尝试从.code.app导入应用程序中导入时,我得到“SystemError:父模块“”未加载,无法执行相对导入”。唯一有效的是prog.app import app
(不带前导点)中现在被认为是非法的
from .code.app import App