Skip to content

optional-dependency-at-import-time (IMP302)

Family: Imports (IMP) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: importing a top-level package or an entry point's module loads, while it loads, a module whose distribution the project declares only in extras, so the import fails without them.

Heuristic

This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.

Experimental

It is new: every report rests on established premises only, but its reports are heuristic until a review of its reports on real code bases certifies its claim, and which distributions provide a module and which modules are base modules can still change. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Reports an import, run while a base module of the project loads, of a module whose distribution the project declares only in extras ([project.optional-dependencies], [tool.poetry.extras]). A base module is a top-level package of the package the project distributes, or a module an entry point names ([project.scripts], [project.gui-scripts], [project.entry-points.<group>], [tool.poetry.scripts]) with the packages holding it. Installing the package without the extra leaves the distribution out, and importing the base module raises ImportError.

The import is in the base module's body, or in the body of a project module it loads while it loads. One report is given per module and module imported, at its first import (the names of one from statement are one import), naming the base module whose import fails, with the imports leading there as related locations. A module that only some other module loads, such as acme.backends.redis for the extra redis, is not reported.

What a report states

A report states that importing the base module it names runs the reported import whenever it loads, and that the project declares every distribution that may provide the imported module only in extras: importing the base module needs them. Unless something else installs them, the import raises ImportError in an installation without the extras.

Its premises, each established or no report:

  • Base module: the module whose load runs the import is a top-level package module of the package code (IMP104 says which code that is), or a module an entry point names, or a package holding one.
  • Chain: the reported import, and each import leading to it from that module, is in a module body (or a class body it runs, or a constant by-name import there), runs on every path through the body, is no lazy import, and loads the module shown, its parent packages first.
  • No handler: no handler may take the ModuleNotFoundError of any of them, which a module that is not installed raises: no except clause naming ModuleNotFoundError, ImportError, Exception, BaseException, a type heki cannot tell is another builtin exception, or a bare except, whose body may end without raising, no with block around one, and no finally body that may leave without raising the error again. A clause whose body raises on every path (raise, raise RuntimeError(...) from e) takes nothing, and a clause that certainly matches hides the clauses after it.
  • Distribution: the distributions that may provide the imported module are found as for IMP301, with its premise that the project holds no copy of the module. The project declares at least one of them, and each one it declares is in an extra and in no dependency.
  • Known dependencies: the project's pyproject.toml has a [project] or [tool.poetry] table, and [project] dynamic lists neither dependencies nor optional-dependencies.

Why is this bad?

An extra is what users opt into: pip install acme installs the package without it, and pip install "acme[redis]" with it. When import acme loads the extra's distribution, the plain install is broken, and the error names a module the user never imported. A command an entry point installs fails the same way before it can say which extra it needs.

Example

[project]
name = "acme"
dependencies = ["httpx"]

[project.optional-dependencies]
redis = ["redis"]
# acme/__init__.py
from acme.cache import Cache
# acme/cache.py
import redis  # IMP302


class Cache:
    def __init__(self, url: str) -> None:
        self.client = redis.Redis.from_url(url)

Use instead:

# acme/cache.py
class Cache:
    def __init__(self, url: str) -> None:
        try:
            import redis
        except ImportError as e:
            raise ImportError("install acme[redis] to use Cache") from e
        self.client = redis.Redis.from_url(url)

Fix safety

No automatic fix.

Options

  • [tool.heki.imports] module-distributions names the distributions that may provide a module (see IMP301).
  • Its reports are errors: lint.severity = { IMP302 = "warning" } makes them warnings.

Known limitations

  • An entry point of a plugin group ([project.entry-points."pytest11"]) is loaded by the program that defines the group, which may itself be the extra's distribution; such a report is right about the import and harmless in practice.
  • A distribution a dependency installs is still reported: the report is about what the project declares.
  • Imports inside functions, lazy imports, and imports on a branch of the module body are not judged, and neither are the modules of a distribution named neither like them nor by the catalog or module-distributions.
  • Dependencies declared outside pyproject.toml are not known.