[英]Weird Python __import__ behavior
我一直在查看以下內容很長一段時間,但無法弄清楚發生了什么。
我正在處理一個現有的 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.