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.
pip install import-linterVerified import paths — ran on the pinned version, not inferred.
Install `import-linter`, then create a `.importlinter` file (or `pyproject.toml`/`setup.cfg`) in your project's root. Define your contracts, specifying rules like 'forbidden' or 'layers'. Finally, run `lint-imports` from your terminal to check for architectural violations. The example demonstrates a forbidden contract preventing imports from `myproject.services` into `myproject.domain`.
Place your configuration in a recognized file (e.g., `.importlinter` or `pyproject.toml`) or use `lint-imports --config path/to/your_config.ini`.
Correctly specify either `root_package = my_single_package` or `root_packages = package_one package_two` in your `[importlinter]` section.
Be aware that contracts will only check imports into external packages, not their internal dependencies.
Check the integer return value of `lint_imports()` to determine contract adherence.
Ensure each contract section has a unique, arbitrary identifier appended after `importlinter:contract:`.
Refactor the offending import in your Python code to comply with the defined contract, or adjust the contract in your '.importlinter' file if the rule is too strict or incorrect for your intended architecture.
Ensure the 'root_package' name in '.importlinter' exactly matches an importable Python package. Verify that the project root (containing the specified package) is in your PYTHONPATH, or that the package is installed (e.g., 'pip install -e .') in the environment where the linter runs.
Add an 'ignore_imports' list to the relevant contract in your '.importlinter' configuration file, specifying the exact import path to be ignored (e.g., 'ignore_imports= my_package.source.importer -> my_package.forbidden.imported').
Ensure your 'root_package' is structured as a proper Python package (a directory with an '__init__.py' file). If you need to lint a single file, consider wrapping it in a minimal package structure or defining contracts that target specific modules within that file's context rather than attempting to set the single file as a top-level 'root_package'.