Skip to content

Lesson 8 of 20 · 17m

Imports Run Code: sys.path, sys.modules, and the Supply Chain

import executes a module's top level through sys.path finders and caches it in sys.modules — the same machinery behind circular imports, python -m, and dependency confusion.

import foo is not a declaration. It is a function call that locates foo, executes its entire top level, and caches the finished module in sys.modules. Every import after the first is a dict lookup. That single fact explains circular-import ImportErrors, why python -m differs from python x.py, editable installs, and half the Python supply-chain attacks on record.

The machinery

sys.path is searched in order — sys.path[0] first (the script's directory for python script.py; python -m pkg runs pkg as __main__ with the current directory resolved differently), then PYTHONPATH, then stdlib, then site-packages. sys.meta_path holds the finders that turn a name into a module spec; the loader executes the module's code and stores it in sys.modules under the dotted name. from mod import x reads x off the module object at import time — if mod is mid-execution because it imports you back, x doesn't exist yet and you get ImportError: cannot import name 'x' from partially initialized module. Plain import mod plus a late mod.x access survives the same cycle. The honest fix for cycles is restructuring or a function-local import mod — importing inside the function defers the lookup until the module is finished.

python -m pip install x and pip install x are not the same command. pip resolves to whatever pip entry point your PATH finds first — possibly bound to a different interpreter than the one you're debugging. -m pip runs pip inside the interpreter you actually invoked: same interpreter, same site-packages, no cross-wiring.

Startup code you never wrote

The interpreter imports site at startup, which runs sitecustomize then usercustomize if they exist on sys.path — module-level code executing before your first line. .pth files in site-packages declare extra path entries with a trapdoor: any line beginning with import is executed, not appended — editable installs use this legitimately, and anyone who can write to your site-packages owns your interpreter. PYTHONPATH prepends to sys.path; a world-writable directory on PYTHONPATH is arbitrary code execution at interpreter start, and the variable is inherited by every child process you spawn.

The supply chain is the import system

Dependency confusion, February 2021: Alex Birsan harvested internal package names from leaked manifests, uploaded same-named packages to public PyPI, npm, and RubyGems with higher version numbers, and resolvers inside Apple, Microsoft, PayPal, and others installed the public copy — over $100,000 in disclosed bounties. Typosquats are the same hole: python3-dateutil shipped a credential stealer dressed as python-dateutil in 2019. In May 2022 the ctx package's maintainer domain lapsed, someone re-registered it, reset the PyPI account by email, and published a version that exfiltrated environment variables — AWS credentials included — to a remote endpoint. None of this is a bug in your code. It is what import means at a trust boundary.

The legitimate plugin mechanism runs on the same machinery: importlib.metadata.entry_points() is how pytest discovers plugins — third-party distributions declare entry points, and import does the rest. importlib.import_module inside a function is the lazy import: it breaks cycles and defers heavy imports — numpy costs hundreds of milliseconds — out of your CLI's startup path.

importlib.reload(mod) re-executes the module in place — and it's a trap that ships to prod in hot-reload tooling: the module object is mutated, but every from mod import x binding elsewhere still points at the old objects. Classes keep their old base classes, so isinstance checks against a reloaded class fail against pre-reload instances.

The practice

Lazy-import inside functions to break cycles and cut startup cost. python -m pip, always. Lock with hashes — pip install --require-hashes, uv.lock, pip-tools output — because the resolver picks "latest" and latest can be hostile. Keep PYTHONPATH empty in production images. Audit site-packages/**/*.pth for import lines on images you didn't build. And when import x appears in a pull request that touches deployment, read x's top level — it runs.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.