我有一个具有以下结构的Python项目:
testapp/
??? __init__.py
??? api
? ??? __init__.py
? ??? utils.py
??? utils.py
Run Code Online (Sandbox Code Playgroud)
所有模块都是空的,除了testapp/api/__init__.py它有以下代码:
from testapp import utils
print "a", utils
from testapp.api.utils import x
print "b", utils
Run Code Online (Sandbox Code Playgroud)
和testapp/api/utils.py其限定x:
x = 1
Run Code Online (Sandbox Code Playgroud)
现在从我导入的根目录testapp.api:
$ export PYTHONPATH=$PYTHONPATH:.
$ python -c "import testapp.api"
a <module 'testapp.utils' from 'testapp/utils.pyc'>
b <module 'testapp.api.utils' from 'testapp/api/utils.pyc'>
Run Code Online (Sandbox Code Playgroud)
导入的结果让我感到惊讶,因为它表明第二个import语句已被覆盖utils.然而,文档声明from语句不会绑定模块名称:
from表单不绑定模块名称:它遍历标识符列表,在步骤(1)中找到的模块中查找每个标识符,并将本地名称空间中的名称绑定到找到的对象.
事实上,当我在终端中使用from ... import ...语句时,不会引入任何模块名称:
>>> from os.path import abspath
>>> …Run Code Online (Sandbox Code Playgroud)