Import Linter
Import Linter is a command-line tool designed to lint your Python architecture by imposing constraints on the imports between your Python modules. It analyzes imports against a set of rules defined in a configuration file, helping to enforce specific architectural styles in complex codebases. The library also provides a browser-based user interface for exploring the architecture of any Python package. It is actively developed, with the current version being 2.11.
Warnings
- gotcha Import Linter searches for configuration in `setup.cfg` (INI format), `.importlinter` (INI format), or `pyproject.toml` (TOML format) by default. Ensure your configuration is in one of these files or specify it explicitly using `--config`.
- gotcha Use `root_package` for a single root package or `root_packages` for multiple root packages in your configuration. Mixing them or omitting both will lead to errors.
- gotcha When `include_external_packages = True` is set, external packages are included in the import graph, allowing you to check imports *to* them. However, Import Linter does not statically analyze the *internal* imports of these external packages.
- gotcha When using the `lint_imports` function programmatically (e.g., in unit tests), it returns an exit code (0 for success, non-zero for failure) rather than raising an exception for broken contracts. Directly asserting the return value (e.g., `assert 0 == lint_imports()`) is the expected pattern.
- gotcha In INI-style configuration files (`.importlinter` or `setup.cfg`), each contract section (e.g., `[importlinter:contract:my-contract-id]`) requires a unique identifier (like `my-contract-id`). Duplicate IDs will result in configuration parsing issues.
Install
-
pip install import-linter
Imports
- CLI
lint-imports
- lint_imports function
from importlinter.cli import lint_imports
Quickstart
# myproject/domain/__init__.py # (empty file) # myproject/domain/models.py # (some model code) # myproject/services/__init__.py # (empty file) # myproject/services/users.py # (some service code) # .importlinter (create this file in your project root) [importlinter] root_package = myproject [importlinter:contract:domain-no-services] name = Domain layer must not import from services layer type = forbidden source_modules = myproject.domain forbidden_modules = myproject.services # Run from your project root in the terminal: # lint-imports