加载模块和初始化模块之间的区别?

Difference between a loaded module and an initialized module?

reference manual 中指出:

A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for sys (various system services), builtins (built-in functions, exceptions and None) and __main__.

我不确定 "initialized" 在这里的意思。我一直认为如果一个模块被加载并出现在 sys.modules:

中就被初始化了

This is a dictionary that maps module names to modules which have already been loaded.

显然,我错了,因为 sys.modules 包含许多其他模块:

python -c "import sys; print(sys.modules.keys() - {'sys', 'builtins', '__main__'})"
{'_stat', 'encodings.aliases', '_sitebuiltins', '_thread', 'io', '_weakrefset', 'genericpath', 'encodings.utf_8', 'codecs', 'os', '_weakref', '_codecs', '_frozen_importlib', '_io', '_frozen_importlib_external', 'os.path', '_warnings', '_bootlocale', '_signal', 'errno', '_imp', 'encodings.latin_1', 'sysconfig', 'marshal', 'encodings', 'usercustomize', 'site', 'posixpath', '_collections_abc', 'posix', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'encodings.cp437', 'abc', 'zipimport', 'stat', '_locale'}

初始化模块和加载模块有什么区别?我在 Python 3.

简单地说:

import 将模块加载到内存中。

当您在模块中调用 class 并使用 .__init__() 函数时,属于此模块的 class 中的某些属性得到更新,然后此模块成为一个初始化模块。

请注意,当您使用该模块时,此过程会隐式发生。

TL;DR

import some_module 加载模块, some_module.some_attribute/function 对其进行初始化。

自编写该文档以来,语言初始化变得更加复杂。 (至少从 Python 1.4 开始几乎没有变化。)sys.modules 中的所有模块都已完全加载和初始化。