Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. This works as I expected in Python 2, but not with Python 3 (3.5 and 3.6 tested). For example:

Python 3.6

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

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. Anyway, since itertools still needs importing in Python 3, I'd be grateful for an explanation.

like image 558
Chris_Rands Avatar asked Feb 17 '17 19:02

Chris_Rands


1 Answers

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

from itertools import islice

which is imported by functools:

from reprlib import recursive_repr

which is imported by types:

import functools as _functools

which is imported by importlib:

import types

which is bootstrapped at interpreter startup because it's where most of the implementation of importing is.

like image 95
user2357112 supports Monica Avatar answered Nov 15 '22 19:11

user2357112 supports Monica