我已经查看以下内容很长一段时间了,但无法弄清楚发生了什么。
我正在处理一个现有的 Python 项目,并且我的目录结构如下(简化):
.
├── functions
│ ├── __init__.py
│ └── test
│ ├── __init__.py
│ ├── file1.py
│ ├── file2.py
│ └── file3.py
├── myexec.py
└── mylib.py
我在 functions
模块的 __init__.py
文件中有以下代码(以及函数内的其他代码):
module_files = ['file1', 'file2', 'file3']
[__import__("functions.test." + module) for module in module_files]
奇怪的是,在下面的行中,使用了名称 test
并且 Python 没有提示它,即使没有任何地方导入 test
>.
我在上面两行之前和之后放置了一些诊断消息,我看到 globals()
使用 test
模块进行了更新。
请注意,test
的__init__.py
为空。
这里可能发生了什么?是否有可能 __import__
行为已以某种方式发生更改并导致在导入 functions.test.fileX
时导入 test
名称?
最佳答案
当导入系统加载functions.test.file1
时,它需要设置属性链,使表达式functions.test.file1
不会产生AttributeError。这意味着
__import__('functions.test.file1')
有副作用
functions.test = <the test module object>
functions.test.file1 = <the file1 module object>
由于functions
包的__init__.py
使用functions
包的属性作为其全局变量,因此全局变量查找名称 test
现在可以找到 functions.test
。
关于python - 奇怪的 Python __import__ 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683614/