意外的导入行为:sys.modules 被检查两次?
Unexpected import behavior: sys.modules is checked twice?
考虑以下场景:
script.py:
import sys
import cant_import_this
print(cant_import_this)
print(cant_import_this is sys)
cant_import_this.py:
import sys
sys.modules['cant_import_this'] = sys
script.py
的输出令人惊讶地是:
<module 'sys' (built-in)>
True
似乎正在发生的事情是:
import cant_import_this
检查 cant_import_this
是否存在于 sys.modules
在sys.modules
中找不到cant_import_this
,所以找到并加载了cant_import_this.py
- 未初始化的
cant_import_this
模块放入sys.modules
- 模块被执行,从
sys.modules
中移除cant_import_this
并替换为sys
- 不是返回模块本身,而是返回查找的结果
sys.modules['cant_import_this']
这个解释正确吗?更重要的是,是否在任何地方记录了这种行为?它可能被认为是一个错误吗?
我在a footnote中找到了答案:
The importlib implementation avoids using the return value directly.
Instead, it gets the module object by looking the module name up in
sys.modules. The indirect effect of this is that an imported module
may replace itself in sys.modules. This is implementation-specific
behavior that is not guaranteed to work in other Python
implementations.
所以这不是一个错误,但也不能依赖它。
考虑以下场景:
script.py:
import sys
import cant_import_this
print(cant_import_this)
print(cant_import_this is sys)
cant_import_this.py:
import sys
sys.modules['cant_import_this'] = sys
script.py
的输出令人惊讶地是:
<module 'sys' (built-in)>
True
似乎正在发生的事情是:
import cant_import_this
检查cant_import_this
是否存在于sys.modules
在cant_import_this
,所以找到并加载了cant_import_this.py
- 未初始化的
cant_import_this
模块放入sys.modules
- 模块被执行,从
sys.modules
中移除cant_import_this
并替换为sys
- 不是返回模块本身,而是返回查找的结果
sys.modules['cant_import_this']
sys.modules
中找不到这个解释正确吗?更重要的是,是否在任何地方记录了这种行为?它可能被认为是一个错误吗?
我在a footnote中找到了答案:
The importlib implementation avoids using the return value directly. Instead, it gets the module object by looking the module name up in sys.modules. The indirect effect of this is that an imported module may replace itself in sys.modules. This is implementation-specific behavior that is not guaranteed to work in other Python implementations.
所以这不是一个错误,但也不能依赖它。