Python 导入迭代,sys.path

Python import iteration, sys.path

所以我想知道,此时我正在阅读一本关于 Python 的书。书中解释如下:

The import algorithm

To truly understand namespace packages, we have to look under the hood to see how the import operation works in 3.3. During imports, Python still iterates over each directory in the module search path, sys.path, just as in 3.2 and earlier.

我的问题是:当未导入 sys 时,python 如何能够遍历 sys.path。此外,如果 python 无需导入即可看到 sys 以遍历 sys.path 为什么我们需要在代码中导入 sys

>>> sys
NameError: name 'sys' is not defined.

>>> import sys
>>> sys
<module 'sys' (built-in)>

没有矛盾。 Python 的 sys 模块 公开了 修改 import 行为的搜索路径配置到 Python 端,但即使没有在你的 Python 代码中导入 sys,解释器知道它自己的配置。

下面CPython source code评论说

/* _PyMem_SetDefaultAllocator() is needed to get a known memory allocator,
   since Py_SetPath(), Py_SetPythonHome() and Py_SetProgramName() can be
   called before Py_Initialize() which can changes the memory allocator. */

这意味着负责设置模块搜索路径的Py_SetPath()可以这么早执行,在任何Python代码可以被解释之前(例如,import 语句),在解释器自己的内存分配器接管之前,它需要自己的内存分配器。

当 Python 解释器的 main() 函数是 运行 时,it can already read the path configuration using Py_GetPath() that calls the internal function _PyPathConfig_Init() 如果有必要,即使在解释器准备好执行 Python代码。