← Back to Python, page 4

python-0076 · Hard senior

How does Python's import system find and load modules, and how can import time be reduced?

import checks sys.modules first; if the module is not cached, finders on sys.meta_path locate it through sys.path, a loader executes the module's code once, and the module object is cached. Startup cost comes from executing heavy top-level code. Measure with python -X importtime and defer expensive imports into the functions that need them.

Full answer
python
import subprocess, sys
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "import json"], capture_output=True, text=True)
lines = [l for l in r.stderr.splitlines() if l.startswith("import time:")]
print(lines[0].split("|")[-1].strip(), "...", lines[-1].split("|")[-1].strip())
print("json" in sys.modules)
import json
print("json" in sys.modules, json.__spec__.origin.endswith("json/__init__.py"))
print(sys.meta_path[0].__name__, len(sys.meta_path) >= 3)

Output:

text
imported package ... json
False
True True
BuiltinImporter True

-X importtime prints a line per module with self and cumulative microseconds; the run shows only the header and the last module name, since times vary. Before import json in this process, json is not in sys.modules; afterwards it is, and its spec records where it was loaded from. sys.meta_path holds the finders, starting with the built-in importer. For command-line tools, moving imports of heavy libraries (pandas, boto3) inside functions can cut startup from seconds to milliseconds. Python 3.12+ also caches more in .pyc files, but executing module bodies still costs time.

python
import subprocess, sys
r = subprocess.run([sys.executable, "-X", "importtime", "-c", "import json"], capture_output=True, text=True)
lines = [l for l in r.stderr.splitlines() if l.startswith("import time:")]
print(lines[0].split("|")[-1].strip(), "...", lines[-1].split("|")[-1].strip())
print("json" in sys.modules)
import json
print("json" in sys.modules, json.__spec__.origin.endswith("json/__init__.py"))
print(sys.meta_path[0].__name__, len(sys.meta_path) >= 3)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • sys.modules caches imports
  • Finders on sys.meta_path locate modules
  • Module code runs once
  • -X importtime measures cost
  • Defer heavy imports

Common mistakes

  • Heavy work at module import time
  • Circular imports between modules

Follow-ups

  • How does importlib.reload behave?
  • What are lazy imports?

Tips

  • Show importtime