python - 奇怪的 Python __import__ 行为

标签 python python-import

我已经查看以下内容很长一段时间了,但无法弄清楚发生了什么。

我正在处理一个现有的 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/

相关文章:

python - 如何提高Python脚本的内存效率

python - Pyspark - 在 groupby 和 orderBy 之后选择列中的不同值

python - 字符串中数字的总和

Python Anaconda - 命令窗口中出现 "import cx_Oracle"错误

python - 导入错误 : No module named ***** in python

python - 当文件名包含句点时如何引用python包

python - 在 Python 中使用变量作为类名?

python - 如何在 python 中为 cosmos db 生成其余授权 token ?

python - 区分本地导入和系统导入

python - 动态重新加载 Cython 模块