Imports and Module Boundaries¶
heki finds import cycles, import-order crashes, and test or development code loaded by a package, enforces import-boundaries contracts, and shows what a module loads with heki inspect --imports (all experimental).
The import rules know when each import runs: while its module loads, when a function runs, or only under TYPE_CHECKING. The rules and the contract can change between releases, and none of them runs without configuration. Rules has one page per rule, and Imports has the settings that say which imports count.
🔁 Cycles and import-order crashes¶
Two modules that import each other while they load are an import cycle. The cycle itself can work, until one import order makes a from M import name run before M has bound the name. Then Python raises ImportError, often only in a test run or an entry point that imports the modules in another order.
fail makes the reports of those rules fail the run, whatever their tier. Without it, a heuristic report is a warning.
# pkg/b.py
from pkg.a import make_a
def make_b() -> str:
return "b"
def both() -> str:
return make_a()
$ heki check --output-format concise
pkg/a.py:1:19: IMP102 [heuristic] `<module>` imports `make_b` from `pkg.b` while `pkg.b` is still loading, at its import of `pkg.a`, and has not bound it: importing `pkg.b` while no module of the import cycle has loaded raises `ImportError` here
pkg/b.py:1:19: IMP101 [heuristic] `<module>` imports `pkg.a` while `pkg.b` loads, which closes the import cycle `pkg.a` -> `pkg.b` -> `pkg.a`
pkg/b.py:1:19: IMP102 [heuristic] `<module>` imports `make_a` from `pkg.a` while `pkg.a` is still loading, at its import of `pkg.b`, and has not bound it: importing `pkg.a` while no module of the import cycle has loaded raises `ImportError` here
Found 3 diagnostic(s) in 3 file(s).
This output is from heki 0.9.0. The full format adds the source line and a help. When one import is on every cycle of the modules, the help names it, as here, where each of the two imports is:
= help: every import cycle of these modules goes through this import: move it into the functions that use it, or make it `lazy`
heki names an import only after one search of the import graph without it finds the cycle gone, and only a change that takes it out of what the rule counts: lazy from Python 3.15 on, where Python allows the keyword, and neither change for a class of imports cycle-edges counts. It names no import whose name code running while its module loads may read: the module body with its class bodies, decorators, defaults, bases, and the annotations the target version evaluates in place, the module's functions these call or apply as decorators, and its __all__. Moved into a function, such an import leaves that read unbound, and made lazy, it loads at the read, still while the module loads. Nor does it name one whose name another project module takes while that module loads: by from m import name, a star import of the module (for a public name), an attribute read off the module object (import m, then m.name), or the module object passed anywhere else (for any name, private ones too), also through a package that re-exports the name. A later statement of the module rebinding the name takes the import out of this only when no code runs between them (no other import, no call), so that no other module can see the import's binding. Moved, the import leaves the module without the name, so the move is offered only while no other module reads it at all; a read in a function leaves lazy, which loads at that read. Otherwise the help names the general ways out: import the name inside the function that uses it, import the module and read the name where it is used, or bind the name before the import of the cycle. IMP301 and IMP302 name the one import every chain from the package to the reported module goes through, and IMP201 with reach = "import-time" the one every chain to the forbidden module goes through, each checked the same way.
📦 What package code loads while it loads¶
A package that works in the repository can fail after pip install: it imports a test helper, a development dependency, or a module that only an extra provides. These rules compare the imports that run while a module loads with the files of the project and the dependencies in pyproject.toml.
With faker declared only in the dev dependency group:
$ heki check --output-format concise
pkg/core.py:1:27: IMP104 [heuristic] `<module>` imports `tests.helpers` while `pkg.core` loads, test code outside the package (`tests/helpers.py`) that the installed package does not include
pkg/fixtures.py:1:19: IMP301 [heuristic] `<module>` imports `faker` while `pkg.fixtures` loads, and the project declares `faker`, which provides it, only in the development group `dev`
Found 2 diagnostic(s) in 5 file(s).
IMP104 leaves out an import under if __name__ == "__main__":, which runs only when the module runs as a script, and gives no report in a project with a setup.py at its root, which may ship any file and which heki does not read. An import that importing the package module runs on every load (in the module body, on every path, not lazy) leaves no premise of its claim open; one in a function, a lazy import, or one on a branch stays heuristic for that reason. The message of one on a branch (or in a class body) says it "may run" while the module loads; a function import says when it runs and a lazy one at its first use.
heki matches a module to its distribution by name (PyYAML provides yaml, Pillow provides PIL). For any other module, module-distributions in [tool.heki.imports] says which distribution provides it.
IMP104 takes the same files for test code as the async rules (see Effects): pytest's default names, an app's tests.py, and the files python_files names in the pytest settings file in use, below its testpaths when it sets them. A package module that imports one of them is reported (heuristic, experimental, opt-in), and tests.py or a configured name is no longer treated as production code.
🧱 Architecture import boundaries¶
import-boundaries says which modules may import which. It counts every import that runs, including one inside a function.
# heki.toml
[[import-boundaries]]
name = "domain-leaf"
importers = ["app.domain.*"]
forbidden-imports = ["app.web", "app.web.*"]
message = "the domain must not know the web layer"
fail = true
A import-boundaries contract that lists every allowed site itself can keep its reports out of a Ratchet baseline with baseline = "never".
app/domain/orders.py imports the web layer inside a function:
$ heki check
app/domain/orders.py:2:31: IMP201 (import-boundary-violation) [error, heuristic] `total` imports `app.web.views.render` when it runs, a forbidden import of `domain-leaf`
|
2 | from app.web.views import render
| ^
= help: the domain must not know the web layer
Found 1 diagnostic(s) in 5 file(s).
The run exits with code 1. A table can also list allowed-imports (with <stdlib> for the standard library) so that everything else is forbidden. With unresolved = "report", an import whose module heki cannot name is reported as IMP202.
With module-reads = "report", a contract also counts a module that the importer reaches by value without importing it: a submodule read through its package (pkg._impl.helper(), register(pkg._impl)), getattr(pkg, "_impl"), sys.modules["pkg._impl"], or a call returning the module. Each is reported under IMP201 as a read (`f` reads `pkg._impl` by value), with the module as its target, so an import and a read of it in one function share one baseline entry. A read keeps the timing an import in its place has: under if TYPE_CHECKING: it counts only with type-checking = "report", and reach = "import-time" counts only the reads of the module body. Tier: heuristic, experimental, contract (Modules reached by value).
An allowed-imports, exempt-importers, or ignored-imports entry can say why it is there: list it in a group with a reason, and set allowance-reasons = "required" on the contract or its defaults table so that an entry without one is a configuration error. With unused-allowances = "warning" or "error" (opt-in, default "ignore"), heki check over the whole project reports each of these entries that allowed no import the contract would report without them.
exempt-decorators accepts the imports (and, with module-reads, the reads of a module) in the body of a function that carries a listed decorator stating a reason (@pytest.mark.allow_json("reads a fixture")), so one test can import what the contract forbids without an entry naming it.
🔬 Inspecting the module load graph¶
heki inspect --imports takes a module name or a glob. For each project module it lists every import with the time it runs and what it loads, and what loading the module loads while it loads:
$ heki inspect --imports app.domain.orders
app.domain.orders (app/domain/orders.py, open code)
imports:
2:31 from-import of `render`: app.web.views (project) [function, in `total`, unconditional]
loads while it loads, at least:
project modules: none
other modules: none
The import is in total, so it runs when total runs, and loading app.domain.orders loads no other module. Use it to see why an import cycle exists, or what an entry point pulls in at start-up. The command is experimental, like the rest of heki inspect.
📋 The rules and the contract¶
| Rule | Reports | Tier |
|---|---|---|
IMP101 |
project modules that import each other while they load, once per group | heuristic, experimental, opt-in |
IMP102 |
a from M import name that raises ImportError when a module of its cycle is imported first |
heuristic, experimental, opt-in |
IMP104 |
a module of the distributed package that imports test code, or a module outside the source roots of a src layout |
heuristic, experimental, opt-in |
IMP301 |
a package module that loads, while it loads, a module provided only by a development dependency | heuristic, experimental, opt-in |
IMP302 |
an import of a top-level package or an entry point's module that loads a module provided only by an extra | heuristic, experimental, opt-in |
IMP201 |
an import that an import-boundaries contract forbids or does not allow |
heuristic, experimental, contract |
IMP202 |
strict mode of import-boundaries: an import whose module heki cannot name |
heuristic, experimental, contract |
Experimental Features says why each one is marked. Which imports count for IMP101 is the cycle-edges setting of [tool.heki.imports]: "body" by default, and "lazy", "function", and "type-checking" on request.
👉 Next steps¶
- Configuration: import-boundaries lists every key of the contract.
- Configuration: imports lists
cycle-edgesandmodule-distributions. - Adopting heki in a code base shows how to start with a baseline, and has a domain boundary with a read-only settings contract to copy.
- State Ownership and Mutation and Async and Execution Effects cover the other contracts.