导入包时 sys.path python 以外的地方查找什么

What places other than sys.path python looks for when importing a package

场景

从包裹中假设 beta:
修改 sys.path 后,导入一个包 alpha 然后还原 sys.path。我尝试导入 alphabeta

中都存在的模块 data_provider

问题是: alpha 中的 data_provider 被选中了 beta,即使 sys.path 现在没有痕迹alpha 的目录

问题:这是一个错误,还是 python 在尝试导入时查看的 sys.path(可能是缓存)以外的其他一些地方一个模块

代码

import os, sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),"src"))

sys.path.insert(0, '../alpha')
import alpha
sys.path.remove('../alpha')

import data_provider as dp

print(sys.path)
print(dp.__file__)

可以找到完整的代码库here

The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if foo.bar.baz was previously imported, sys.modules will contain entries for foo, foo.bar, and foo.bar.baz. Each key will have as its value the corresponding module object.

During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes. However, if the value is None, then a ModuleNotFoundError is raised. If the module name is missing, Python will continue searching for the module.

在此处阅读更多相关信息 https://docs.python.org/3/reference/import.html#the-module-cache