【发布时间】:2015-04-30 17:45:30
【问题描述】:
我有一个 Python 项目,其结构如下:
testapp/
├── __init__.py
├── api
│ ├── __init__.py
│ └── utils.py
└── utils.py
除了testapp/api/__init__.py,所有模块都是空的,它的代码如下:
from testapp import utils
print "a", utils
from testapp.api.utils import x
print "b", utils
和定义x的testapp/api/utils.py:
x = 1
现在我从根目录导入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'>
导入的结果让我吃惊,因为它表明第二个import 语句已经覆盖了utils。然而文档声明from statement will not bind a module name:
from 表单不绑定模块名称:它通过列表 标识符,在步骤中找到的模块中查找它们中的每一个 (1),并将本地命名空间中的名称绑定到对象,从而 找到了。
确实,当我在终端中使用from ... import ... 语句时,不会引入任何模块名称:
>>> from os.path import abspath
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
我怀疑这与 Python 有关,在第二个 import 语句时,尝试导入引用 testapp.utils 的 testapp.api.utils 并失败但我不确定。
这里发生了什么?
【问题讨论】:
-
我没想到会出现这种行为,我也很想听到答案。
-
你能从各种 utils 文件中添加一些代码吗?
-
@NikosM。正如我提到的,所有其他文件都是空的。
-
是的,我明白了,你必须使用
from module.name import property as alias结构来避免命名空间冲突,因为本地命名空间对于你的 init 文件是相同的 -
如果
testapp/utils.py(以及testapp/api/__init__.py中的前两个非空行)被删除,这个例子会更清楚。它们对问题并不重要,只是分散注意力。