Make Python fail when a boundary is crossed
Python won't stop you from importing a module's internals. Here's the real config that makes your linter and tests fail when anyone tries.
Everything in the last few notes depends on boundaries holding: nobody imports a package’s internal files, nobody imports a vendor library outside its adapter, and lower layers never reach up into higher ones. The problem is that Python doesn’t enforce any of that. A leading underscore is a polite request. Anyone can type from gigbook.storage._s3_song_storage import S3SongStorage and it’ll work just fine.
Rules that depend on everyone remembering them don’t survive a deadline. So I make the build enforce them. If a boundary is crossed, something goes red, and the change doesn’t merge.
I use three layers of checking, each catching something the others can’t:
- Ruff bans vendor imports file by file. It’s fast and shows up right in the editor.
- Import Linter checks the whole import graph: layers, and which packages may import what.
- A small pytest test catches anyone importing another package’s underscore files.
All of the config below comes from the gigbook example used throughout these notes, and I’ve run every check against it both ways: passing on the clean code, and failing on purpose-made violations.
The package layout
The rules are only as clear as the layout they protect:
src/gigbook/
├── main.py
├── setlists/ A feature: uses app_context and nouns
├── app_context/ Builds everything: uses chord_charts, config, storage
├── chord_charts/ The only package that makes HTTP calls (httpx)
├── config/ The only package that reads the environment
├── storage/ The only package that talks to S3 (boto3)
└── nouns/ The program's dictionary. Imports nothing else in gigbook.
Each package’s __init__.py is its public interface. Files starting with an underscore are internal to their package.
1. Ruff: ban vendor imports outside their adapter
Ruff is a Python linter, and its TID251 rule (banned-api) flags any import of a module or name you list. Ban each vendor everywhere, then allow it in exactly one file with per-file-ignores. The ban message tells whoever hits it where to go instead:
# pyproject.toml
[tool.ruff.lint]
extend-select = ["TID251"]
[tool.ruff.lint.flake8-tidy-imports.banned-api]
"boto3".msg = "Use gigbook.storage. Only its internals talk to S3."
"botocore".msg = "Use gigbook.storage. Only its internals talk to S3."
"httpx".msg = "Use gigbook.chord_charts. Only its internals make HTTP calls."
"os.environ".msg = "Read settings from app_context.config."
"os.getenv".msg = "Read settings from app_context.config."
[tool.ruff.lint.per-file-ignores]
"src/gigbook/chord_charts/_http_chord_chart_service.py" = ["TID251"]
"src/gigbook/config/_environment_config.py" = ["TID251"]
"src/gigbook/storage/_s3_song_storage.py" = ["TID251"]
Notice os.environ and os.getenv in there. That’s the config rule from the vendor note, enforced: nothing but EnvironmentConfig gets to read the environment. A feature that tries gets this:
TID251 `boto3` is banned: Use gigbook.storage. Only its internals talk to S3.
TID251 `os.environ` is banned: Read settings from app_context.config.
2. Import Linter: layers and forbidden imports
Ruff looks at one file at a time. Import Linter builds the whole program’s import graph and checks it against contracts you write in pyproject.toml. Two kinds of contract do most of the work.
A layers contract lists packages from highest to lowest. Higher layers may import lower ones, never the reverse. Packages on the same line, separated by |, are siblings that must stay independent of each other:
[tool.importlinter]
root_package = "gigbook"
# Lets contracts talk about third-party packages like boto3, not just our own.
include_external_packages = true
[[tool.importlinter.contracts]]
name = "Layers: higher layers may import lower ones, never the reverse"
type = "layers"
layers = [
"gigbook.main",
"gigbook.setlists",
"gigbook.app_context",
"gigbook.chord_charts | gigbook.config | gigbook.storage",
"gigbook.nouns",
]
That one contract says a lot. Nouns can’t depend on anything. Storage can’t reach into chord charts or the other way around. Nothing below app_context can see it, so no low-level module can go grab a dependency for itself. And the app’s flow reads top to bottom, starting from main.
A forbidden contract says some modules may not import others. Pointed at the whole root package, with the adapter’s own imports listed as the exceptions, it means a vendor can be used in exactly one place:
[[tool.importlinter.contracts]]
name = "Only the storage package talks to S3"
type = "forbidden"
source_modules = ["gigbook"]
forbidden_modules = ["boto3", "botocore"]
ignore_imports = [
"gigbook.storage._s3_song_storage -> boto3",
"gigbook.storage._s3_song_storage -> botocore",
]
[[tool.importlinter.contracts]]
name = "Only the chord chart package makes HTTP calls"
type = "forbidden"
source_modules = ["gigbook"]
forbidden_modules = ["httpx"]
ignore_imports = ["gigbook.chord_charts._http_chord_chart_service -> httpx"]
(This overlaps with the Ruff ban on purpose. Ruff gives fast feedback in the editor; Import Linter is the one that sees the whole graph, so it catches the same thing even when someone silences a lint warning.)
Run it with lint-imports, with your package installed in the environment (pip install -e . works for a src/ layout). When a feature imports boto3 and nouns imports storage, here’s what it says:
Contracts: 1 kept, 2 broken.
Layers: higher layers may import lower ones, never the reverse
--------------------------------------------------------------
gigbook.nouns is not allowed to import gigbook.storage:
- gigbook.nouns._setlist -> gigbook.storage (l.15)
Only the storage package talks to S3
------------------------------------
gigbook is not allowed to import boto3:
- gigbook.setlists._shortcut -> boto3 (l.3)
It names the file and line. There’s no arguing with it, which is the point.
3. A test that guards every package’s internals
The last rule is “never import another package’s underscore files,” and neither tool above expresses it directly. So it’s a test. It reads every source file with Python’s own parser, finds each import of a module with an underscore segment (like gigbook.storage._s3_song_storage), and fails unless the importing file lives inside the package that owns it:
"""Fails the build when code reaches into another package's internals.
A file whose name starts with an underscore is internal to its package. Only
files inside that package may import it; everyone else goes through the
package's __init__.py.
"""
import ast
from collections.abc import Iterator
from pathlib import Path
SOURCE_ROOT = Path(__file__).parent.parent / "src"
ROOT_PACKAGE_NAME = "gigbook"
def test_no_module_imports_another_packages_internals() -> None:
violations = [
f"{importer} imports {imported}"
for importer, imported in _find_internal_imports()
if not _is_inside(importer, _owning_package(imported))
]
assert not violations, "Imports that skip a package's public interface:\n" + "\n".join(
violations
)
def _find_internal_imports() -> Iterator[tuple[str, str]]:
"""Every (importing module, imported module) pair where the imported module is internal."""
for source_file in (SOURCE_ROOT / ROOT_PACKAGE_NAME).rglob("*.py"):
importer = _to_module_name(source_file)
for imported in _imported_module_names(source_file, importer):
if imported.startswith(ROOT_PACKAGE_NAME + ".") and _is_internal(imported):
yield importer, imported
def _imported_module_names(source_file: Path, importer: str) -> Iterator[str]:
for node in ast.walk(ast.parse(source_file.read_text(), filename=str(source_file))):
if isinstance(node, ast.Import):
yield from (alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom):
module = _resolve_relative_import(
node, importer, is_package=source_file.name == "__init__.py"
)
yield module
# `from gigbook.storage import _song_serialization` reaches inside, too.
yield from (
f"{module}.{alias.name}" for alias in node.names if _is_internal_segment(alias.name)
)
def _resolve_relative_import(node: ast.ImportFrom, importer: str, is_package: bool) -> str:
"""Turns `from ._song import Song` into the absolute module name it refers to."""
if node.level == 0:
return node.module or ""
# An __init__.py is its package; any other module's package is its parent.
package_segments = importer.split(".") if is_package else importer.split(".")[:-1]
base = ".".join(package_segments[: len(package_segments) - (node.level - 1)])
return f"{base}.{node.module}" if node.module else base
def _is_inside(module_name: str, package_name: str) -> bool:
return module_name == package_name or module_name.startswith(package_name + ".")
def _is_internal(module_name: str) -> bool:
return any(_is_internal_segment(segment) for segment in module_name.split("."))
def _is_internal_segment(segment: str) -> bool:
return segment.startswith("_") and not segment.startswith("__")
def _owning_package(module_name: str) -> str:
"""The package that owns an internal module: everything before its first underscore segment."""
segments = module_name.split(".")
first_internal_index = next(
index for index, segment in enumerate(segments) if _is_internal_segment(segment)
)
return ".".join(segments[:first_internal_index])
def _to_module_name(source_file: Path) -> str:
relative_parts = source_file.relative_to(SOURCE_ROOT).with_suffix("").parts
return ".".join(relative_parts[:-1] if relative_parts[-1] == "__init__" else relative_parts)
gigbook/storage/__init__.py importing gigbook.storage._s3_song_storage passes, because it’s inside the package. A setlist file doing the same thing fails, with a list of exactly which imports skipped the interface:
AssertionError: Imports that skip a package's public interface:
gigbook.setlists._shortcut imports gigbook.storage._s3_song_storage
gigbook.setlists._shortcut imports gigbook.storage._song_serialization
It’s plain Python with no dependencies beyond pytest, so it’s easy to copy into any project. Change ROOT_PACKAGE_NAME and it works.
Run them where nobody can skip them
None of this helps if it only runs when someone remembers. All three go in CI, on every pull request, and the pull request can’t merge unless they pass:
ruff check .
lint-imports
pytest
I like running them locally too, before pushing, so the boundary violation shows up while I still remember why I wrote the import.
Why bother
Because the architecture lives in these rules. The day someone imports boto3 straight into a feature “just this once,” the storage adapter stops being the only place that knows about S3, and the promise that “switching storage is a one-module change” quietly stops being true. Nobody notices until it’s expensive. With the checks in place, that shortcut is a red build in the first five minutes instead of a surprise a year later. The architecture stops being a diagram on a wiki page and becomes something the code can’t drift away from.