意外的导入行为: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

似乎正在发生的事情是:

  1. import cant_import_this 检查 cant_import_this 是否存在于 sys.modules
  2. sys.modules中找不到
  3. cant_import_this,所以找到并加载了cant_import_this.py
  4. 未初始化的cant_import_this模块放入sys.modules
  5. 模块被执行,从sys.modules中移除cant_import_this并替换为sys
  6. 不是返回模块本身,而是返回查找的结果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.

所以这不是一个错误,但也不能依赖它。