Import, end to end

import does not include a file — it executes it, exactly once per process. Hence shared module state, circular imports, “where to patch a mock”, and half the oddities QA keeps seeing.

L1 · 9 minL2 · 10 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
# pkg/__init__.py contains print("executing")
import pkg
import pkg
import pkg
executing
Three imports, one line of output.
Snippet B
# pkg/a.py:  from pkg.b import helper
# pkg/b.py:  from pkg.a import go
import pkg.a
ImportError: cannot import name 'go' from partially
initialized module 'pkg.a' (most likely due to a
circular import)
The key words are partially initialized.
Snippet C
# src.py:      def now(): return "real time"
# consumer.py: from src import now
#              def report(): return f"report: {now()}"

with patch("src.now", return_value="FAKE"):
    print(consumer.report())

with patch("consumer.now", return_value="FAKE"):
    print(consumer.report())
report: real time
report: FAKE
We patch the same function by two paths. Only one works.
Snippet D
import pkg
pkg.VERSION = "changed"

import pkg as pkg2
print(pkg2.VERSION)
changed
A different name, a different import — the same state.

2Mechanism

A module is an object. Its namespace is an ordinary dictionary, the very one from lesson 05.

import executes the file from top to bottom in that dictionary — like the body of a function or a class.

The result is cached in sys.modules by name. A repeated import fetches the ready object and executes nothing.

Consequence 1 · a module executes once, and its state is shared

Snippets A and D. The first import executes the file and puts the object into sys.modules; all subsequent ones return that same object. So any change to a module attribute is visible everywhere it was imported — regardless of the name it was imported under.

Two things follow at once. A good one: a module is a ready-made singleton, and no separate pattern is needed for it. A bad one: everything at the top level of a module lives for the whole process — caches, connections, counters, modified class attributes. This is the source of “the test passes alone and fails in the suite”: state leaks between tests, and the order merely reveals the problem.

Consequence 2 · from x import y binds a name rather than referring to the module

This is the most common blind spot, and snippet C exposes it. from src import now does literally the following: imports src, takes now from its dictionary and puts it under the same name into the dictionary of the consuming module. The result is two independent entries pointing at one object.

Substituting src.now rewrites the entry in src's dictionary. The entry in consumer's dictionary does not change — it still points to the old function. That is why you patch where it is used: patch("consumer.now").

This is not a property of the mocking library but a direct consequence of a name being a binding (lesson 01) and a module's namespace being a dictionary. And the same explains why import src with the access src.now() can be patched either way: access through the module reads src's dictionary every time.

Consequence 3 · a circular import sees a half-built module

Snippet B. To protect against infinite recursion, Python puts the module object into sys.modules before executing its body. So in a cycle the second import gets an object in which only part of the lines have run.

What happens next depends on the form. from pkg.a import go requires the name right now — and fails if its definition has not been reached yet. Whereas import pkg.a with the access pkg.a.go() inside a function will work: by the time of the call the module is fully assembled.

Hence three ways to fix it, all derived from the mechanism: move the import inside a function, import the whole module instead of a name from it, or pull the shared part out into a third module, breaking the cycle.

Consequence 4 · an import can do anything

Since it is the execution of ordinary code, anything can happen on import: a connection opens, a file is read, a handler is registered, a request goes out to the network. The language does not forbid this and cannot.

There are two practical consequences. The first is startup time: heavy work at the top level of a module runs on every start of the process, and in a CLI tool or a lambda you can see it with a stopwatch. The second is order: a side effect happens at the moment of the first import, and that depends on who imported whom first.

3Limits of the model

Where this stops holding

sys.modules can be changed by hand — test substitutions and lazy loaders rest on this. But deleting an entry does not “unload” the module: the old object is alive while something refers to it, and a second import will create a second module with separate classes. Hence the mysterious isinstance returning False for an object of “the same” class.

importlib.reload does not reload the world. It re-executes the body in the same dictionary, but objects and classes already created stay old, and other modules keep their bindings to the previous functions — straight from consequence 2.

The search path is not only sys.path. The mechanism is extensible: sys.meta_path and sys.path_hooks let you import from anywhere — from an archive, from the network, from a database. Zip applications and plugin systems rest on this.

4Root

Root R7: import is execution. The decision was made at the very beginning and follows from the general model: since def and class execute, and a module is just a file of code, the module executes too. The language has no separate “inclusion” phase.

Hence also the fact that import is an ordinary statement rather than a preprocessor directive: it can be written inside a function, under an if, in a loop. That is exactly what is used to break cycles and to load heavy dependencies lazily.

The price is the absence of a static picture of the program. The compiler does not know what comes from where; tools are forced to guess; an import error is discovered only at run time. In return, extensibility: replacing the import mechanism is an ordinary task, not a hack.

5Analogy

The closest exact analogy is static initialization in C++. A global object with a constructor runs code before main, exactly once, and the order between translation units is undefined — the famous “static initialization order fiasco”. A Python module behaves the same way: top-level code is a constructor that runs once on first access.

And the problem is essentially the same: if one module at the top level depends on another having already run, order starts to matter — and it is determined by who imported whom first. The cure coincides in spirit too: in C++ lazy initialization through a function with a local static is used; in Python, work is moved out of the module body into a function that is called explicitly.

The difference is one, and in Python's favour: its order is at least deterministic and visible in the code, rather than left to the linker.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why does a circular import sometimes work and sometimes fail?

Because a module gets into sys.modules before its body executes — and the only question is whether the needed name has run yet.

When a imports b, and b imports a back, the second import finds a in the cache and does not start it again — otherwise there would be infinite recursion. But at that moment the body of a has been executed only partially.

# a.py
X = 1
import b
Y = 2

# b.py
import a
print(a.X)      # → 1     this line has already run
print(a.Y)      # → AttributeError: partially initialized module

Hence all the observed behaviour: import a inside a cycle usually works (we get the module object and access attributes later), while from a import Y fails, because it requires Y to exist already at the moment of the import.

How to fix it, in order of preference. First — move the shared part into a third module: a cycle usually means two modules share an entity that has no place of its own. Second — import inside a function rather than at the top level: by the time of the call both modules are ready. Third — if TYPE_CHECKING, if the import is needed only for annotations (lesson 18).

What not to do: shuffle the imports around until it works. That fixes the symptom, and the next person to add a line will break it all again.

Why must a mock be patched where it is used rather than where it is defined?

Because from x import y creates a separate binding in the importing module, and a substitution in the original module does not touch it.

# utils.py
def now(): return "real time"

# report.py
from utils import now          # its own reference to the function object
def make(): return f"report: {now()}"
from unittest.mock import patch
import report

with patch("utils.now", return_value="FAKE"):
    print(report.make())       # → report: real time   did not work

with patch("report.now", return_value="FAKE"):
    print(report.make())       # → report: FAKE        worked

The reason comes straight from the mechanism: from utils import now executes once when report is imported and writes the current value into report's globals. From then on these are two independent entries in two dictionaries, pointing at one object. Changing one does not touch the other.

Whereas import utils + utils.now() behaves differently: there the module attribute is read on every call, and a patch in utils is visible.

The rule fits in one phrase: “patch where it is looked up, not where it lives”. And that is exactly why mock.patch takes a string, not an object — from an object you cannot tell in whose namespace to substitute it.

Why is from module import * bad?

Because it makes it impossible to answer “where did this name come from”, both for a person and for tools.

The concrete consequences, in decreasing order of harm:

  • Silent overwriting. Two such imports in a row — and the second quietly shadows the names of the first. The error will show up far from the spot.
  • Tools go blind. A linter cannot tell a typo from an imported name, the IDE will not find the definition, mypy loses the types.
  • The dependency becomes implicit. The code does not show what exactly is used — so you can neither narrow the import nor understand what will break on an upgrade.
  • More is imported than you see. Without __all__, all the module's public names arrive, including its own imports.
# mod.py
import os, sys
PUBLIC = 1
_private = 2

# another file
from mod import *
print(PUBLIC, os)     # → 1, and the os module came along too

__all__ in a module limits the list, but relying on someone else's discipline is not worth it.

Where it is acceptable: in an interactive session, where typing speed matters; in a package's __init__.py that deliberately re-exports its public API — and there always with __all__; in configuration modules like settings_local, where shadowing is the goal. In all other code, an explicit list of names.

Why __init__.py, if packages work without it?

They work, but become a different kind of package — with different behaviour that people usually discover in production.

Since 3.3 (PEP 420) a directory without __init__.py becomes a namespace package. It was designed for one task: to spread one logical package across several places on disk, so that company.tools and company.web can be installed as separate distributions.

The differences that bite:

  • A namespace package is assembled from all matching directories on sys.path. A directory name that happens to coincide somewhere else — and the package's contents quietly mix.
  • A typo in the name does not give an import error at once. An empty namespace package imports successfully and fails only on access to a submodule.
  • Tools behave differently. Some build tools and find_packages() do not see them by default, and the directory does not make it into the wheel.
import mypkg
print(mypkg.__path__)
# a regular package:  ['/path/mypkg']
# namespace:          _NamespacePath(['/path/mypkg', '/other/path/mypkg'])

The rule is simple: unless you are building a package spread across distributions, put an __init__.py in, empty. It costs zero bytes and makes the behaviour predictable. Namespace packages are a special tool, not “the modern way to do without the file”.

Bottom line. A module is an object, its namespace is a dictionary, and import executes the file from top to bottom and caches the result in sys.modules. Hence: a module body runs exactly once per process, so everything at the top level lives for the whole run and leaks between tests. from x import y creates a separate binding in the consumer's dictionary, so substitution must happen where the name is used, not where it is defined — this is a question of name binding, not of the mocking library. The module object gets into the cache before its body executes, to cut off recursion, so a circular import sees a half-built module and fails on from ... import but survives an import of the whole module. And since this is ordinary execution, anything can happen on import — including seconds of work at startup and side effects whose order depends on who imported whom first.
From here on — optional
counterfactualC, C++ modules, JavaTextual insertion by a preprocessor versus execution — and why Python has no double-inclusion problem

C with its #include is the opposite pole: the preprocessor literally pastes the file's text at the point of inclusion, before any compilation. Hence the whole set of problems Python does not have: double inclusion (cured by #pragma once or an include guard), an order of inclusions that affects meaning, and bloated translation units. Python solves this differently — not by protecting against repeated inclusion, but by repeated execution simply not happening: sys.modules is a built-in include guard.

But C has what Python does not: a complete static picture. The linker knows all the symbols, and an unresolved reference is a build error, not a runtime one.

C++20 modules are an attempt to get both properties: an import unit is compiled once, the interface is separated from the implementation, order does not matter. That is closer to Python in semantics, but stays at compile time.

Java compiles each class separately and loads it by name at runtime — a mechanism closer to Python's, including the ability to replace the loader. But import in Java merely shortens names, executing nothing.

🐛 bugModule state leaking between testsA test is green alone and red in the suite — because the module ran once, and there are many tests

A classic that QA sees every week, while the cause is usually sought in the wrong place.

# settings.py
FEATURES = load_features()          # will run once per process

# test_a.py
def test_new_flow():
    settings.FEATURES["new_flow"] = True     # switched on for its own test
    assert run() == "new"

# test_b.py
def test_old_flow():
    assert run() == "old"                    # fails if test_a ran earlier

Both tests are correct on their own. But settings is imported once, and the FEATURES dictionary is one for the whole run: the first test changed it, the second got it changed. The order of the tests does not create the problem, it only reveals it — hence “fails every other time” and “fails only in CI, where the order is different”.

Review lets it through because the diff shows one test, while what broke is another one, in another file.

@pytest.fixture(autouse=True)
def _restore_features():
    saved = copy.deepcopy(settings.FEATURES)
    yield
    settings.FEATURES.clear()
    settings.FEATURES.update(saved)

Note the deepcopy — a shallow copy is not enough here for the reason from lesson 01, and clear+update instead of assignment is needed because other modules hold a binding to that very dictionary object (consequence 2), and replacing it with a new one would not reach them.

The general rule: mutable state at the top level of a module is a process-wide global variable. Either do not change it, or restore it explicitly.

⚡ techniqueFind what slows down startuppython -X importtime shows the import tree with milliseconds — usually a couple of lines are to blame

A CLI tool takes a second and a half to start, and nobody knows why. The answer is one command.

python -X importtime -c "import myapp" 2>&1 | sort -k2 -n -r | head -20

The output is a tree with two columns: the module's own time and the cumulative time with dependencies.

import time: self [us] | cumulative | imported package
import time:       716 |       1270 |   json.scanner
import time:       593 |       9077 |   json.decoder
import time:      1065 |      10795 | json

Look at cumulative for the top-level ones: there you see at once that half the startup is taken by some library imported for the sake of one function in a rare branch.

The cure follows from consequence 4: since import is an ordinary statement, it can be moved to where it is needed.

# before: at the top level
import pandas as pd

# after: inside the function that alone uses it
def export_excel(rows):
    import pandas as pd
    ...

The cost is microseconds for a lookup in sys.modules on every call (consequence 1 guarantees the body runs only once). For a function called in a loop, better move it back out; for a rare branch the gain is direct.

Where this is critical: CLI tools, serverless with a cold start, tests where the interpreter is brought up many times. In a long-lived service it does not matter at all.

💻 terminalCheck it in the REPLFour snippets plus reload, deleting from sys.modules, and __main__

Copy the snippets and run them, checking against your prediction. Then:

import sys, json
del sys.modules["json"]
import json as json2
print(json is json2)
# Why False? What now happens with isinstance for classes from there?

# in the file script.py:
print(__name__)
# What is printed when it is run, and what when it is imported?
# And why does multiprocessing with spawn break without this check?

import importlib, mymod
from mymod import f
importlib.reload(mymod)
print(f is mymod.f)
# Why False? Which consequence explains it?

import sys
print(len(sys.modules))
# How many modules are already loaded in an empty interpreter?

The third question is a direct check of consequence 2: reload creates new functions in the module's dictionary, while the binding in your namespace points to the old one.

sourceimportlib and unittest.mockWhere the mechanism is visible as a design decision, not as theory

Lib/importlib/_bootstrap.py. The whole import mechanism, written in Python and frozen into the interpreter at build time. Find _find_and_load — consequence 3 is literally visible there: the module object is put into sys.modules before exec_module is called, and right next to it is a comment about circular imports.

Lib/unittest/mock.py, the _get_target function. Here you can see that patch("a.b.c") is simply splitting a string into a module and an attribute name, followed by a setattr. No magic: the library rewrites an entry in a dictionary, and which one is decided by you, with a string. Understanding consequence 2 closes the question “where to patch” for good.

Lib/site.py. The module that runs on every interpreter start and assembles sys.path. Useful to read once, so that sys.path stops being a given.

L2What happens between import and executionFinders, loaders, sys.modules and the bytecode cache

From L1 you know that an import executes the file and caches the object. Here: what lies in between.

The sequence for import pkg.mod:

  1. Check sys.modules["pkg.mod"]. If it is there — return it and finish.
  2. Import the parent pkg, if it is not there yet.
  3. Walk sys.meta_path — the list of finders. Each is asked whether it can find the module; there are three standard ones, and the last searches sys.path.
  4. The finder returns a spec: the name, the loader, the path to the file.
  5. An empty module object is created and put into sys.modules.
  6. The loader executes the code in the module's dictionary. If it raised an exception, the entry is removed from sys.modules.

Step 5 before step 6 is the very place “partially initialized module” grows from.

The bytecode cache. A file is compiled into bytecode and stored in __pycache__ with a fingerprint of the source — by default its modification time and size. So a repeated run skips compilation, but not execution: the module body always runs. Deleting __pycache__ will not speed up startup; it can be sped up only by not importing what is not needed.

import sys
print(len(sys.modules))
# → about 60 modules are already loaded in an “empty” interpreter

import json
print(json.__spec__)
# → ModuleSpec(name='json', loader=..., origin='.../json/__init__.py')
L3Where this is in the CPython sources_bootstrap.py, import.c, PEP 451

Tag v3.11.15.

  • Lib/importlib/_bootstrap.py, the functions _find_and_load and _load — the whole sequence from L2 in readable Python.
  • Python/import.c — the C part: working with sys.modules, import locks, initializing built-in modules.
  • Lib/importlib/_bootstrap_external.py — searching the file system and the bytecode cache: the format of the .pyc header is there too.
  • PEP 451 — module specs; the current architecture of finders and loaders is described there.
connectionsWhere this leadsL01, L05, L14 · the contrast with #include and C++ static initialization
root R7 · Import is code execution
← foundation L01 · Name, object, reference — from x import y creates a binding, and hence “where to patch”
← foundation L05 · dict and hashability — a module's namespace is a dictionary
↔ contrast #include in C: textual insertion and an include guard versus the cache in sys.modules
↔ contrast C++ static initialization: the same “constructor before main” and the same ordering problem
→ next L16 · Packages and rewriting — what happens a level up, at installation
not covered here Namespace packages and the structure of distributions — in L16
readingFurther reading_bootstrap.py 🟥 · The import system 🟧 · PEP 451 🟦

Written by · The Python Canon