简体   繁体   English

为什么未在Python 3的“ sys.modules”中导入模块?

[英]Why are modules that haven't been imported in 'sys.modules' in Python 3?

I was reading how to check if a python module has been imported and the instructions seems clear, check for the module in the sys.modules . 我正在阅读如何检查是否已导入python模块 ,并且说明似乎很清楚,请在sys.modules检查该模块。 This works as I expected in Python 2, but not with Python 3 (3.5 and 3.6 tested). 这可以按我在Python 2中预期的方式工作,但不适用于Python 3(已测试3.5和3.6)。 For example: 例如:

Python 3.6 Python 3.6

>>> import sys
>>> 'itertools' in sys.modules
True

Python 2.7 Python 2.7

>>> import sys
>>> 'itertools' in sys.modules
False

I note that, itertools is described as a 'built-in' in the Python 3 sys.modules dict ( <module 'itertools' (built-in)> ), and not in Python 2 so maybe that's why it's in sys.modules prior to being imported, but it's not listed as a built-in . 我注意到, itertools在Python 3 sys.modules dict<module 'itertools' (built-in)> )中被描述为“内置”,而不是在Python 2中,所以也许这就是它在sys.modules中的原因在导入之前,但未作为内置项列出 Anyway, since itertools still needs importing in Python 3, I'd be grateful for an explanation. 无论如何,由于itertools仍然需要在Python 3中导入,因此我很感谢您提供一个解释。

They have been imported, just not by you. 它们被导入,只是不是您导入的。 Exactly what parts of interpreter startup caused the module to be loaded are unimportant implementation details, but you can trace possible paths if you want. 解释器启动的确切原因是导致模块加载的是不重要的实现详细信息,但是您可以根据需要跟踪可能的路径。 For example, itertools is imported by reprlib 例如, itertoolsreprlib导入

from itertools import islice

which is imported by functools : 这是由functools导入的:

from reprlib import recursive_repr

which is imported by types : 通过types导入:

import functools as _functools

which is imported by importlib : 这是由importlib导入的:

import types

which is bootstrapped at interpreter startup because it's where most of the implementation of importing is. 它在解释器启动时被引导,因为它是大多数导入实现的地方。

It appears that in Python 3, the itertools extension is actually compiled into the main Python binary unlike Python 2. If you do a 看来在Python 3中,itertools扩展实际上是编译为Python 2中的主要二进制文件,这与Python 2不同。

import sys

and then a 然后一个

'itertools' in sys.builtin_module_names
>> True

it is clear. 很明显。 Doing the exact same steps in a Python 2.x console results in a False . 在Python 2.x控制台中执行完全相同的步骤会导致False

As per the docs , builtin_module_names comprises of 'modules that are compiled into this Python interpreter' . 根据文档builtin_module_names包含“已编译到此Python解释器的模块”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM