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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With