所以我想知道,此时我正在阅读一本关于 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 端,但即使不导入 sys
在你的 Python 代码中,解释器知道它自己的配置。
在下面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使用 Py_GetPath()
的路径配置调用内部函数 _PyPathConfig_Init()
如有必要,即使在解释器准备好执行 Python 代码之前,这样做也是安全的。
关于Python 导入迭代,sys.path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945739/