circular-import-failure (IMP102)¶
Family: Imports (IMP) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix
Opt-in: a from M import name that raises ImportError when a module of its import cycle is imported before the others, because M is still loading and has not bound name.
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 imports and code stop a run 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 a from M import name that raises ImportError when a module of its import cycle is
imported before the other modules of the cycle have loaded. Importing that module runs its body,
and the imports in module bodies lead from it to the statement while M is still loading: M
is paused at the import that started the chain, and has not bound name yet. Python then raises
ImportError: cannot import name 'name' from partially initialized module 'M' (most likely due to
a circular import).
heki finds it without configuration. For each group of the project's modules that import each
other while they load, it imports each module of the group first in turn, and each package
holding one whose __init__.py imports the group: the module's parent packages load first, then
the module bodies run in order through their imports, and each import of a module that has not
loaded yet runs that module's body before the import goes on. One report is given per failing
statement, naming the modules whose import fails there, with the imports of the chain from the
first of them as related locations.
Only from M import name fails this way. import M and import M as m take the module while
it is still loading and do not fail there, and neither does from pkg import sub of a submodule
pkg.sub, which Python finds in sys.modules.
What a report states¶
A report states that importing one of the modules it names, while no module of the import cycle
has been imported in the process, does not complete: unless code that runs before raises first,
the chain of imports shown reaches the reported statement while M is loading and has not bound
name, and the statement raises ImportError.
Its premises, each established or no report:
- Chain: each import of the chain 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 name resolved against the project's modules, a
fromimport split between a submodule and an attribute as Python splits it, and the parent packages of a module loading first. The reported statement is such an import too, and takes the name fromMitself. - Not loaded before: each module the chain enters has not loaded yet. A module of the cycle has not, by the claim; a module outside it has not when its import imports a module of the cycle whenever it runs, and every way from its imports to the cycle is an import in a module body that heki names. Otherwise an import of a module outside the cycle that may load one of the cycle stops the run.
- No handler: no handler takes the
ImportErroron the way, a plain one: noexceptclause namingImportError,Exception,BaseException, a type heki cannot tell is another builtin exception, or a bareexcept, whose body may end without raising, nowithblock, and nofinallybody that may leave without raising it again, around an import of the chain or the statement.except ModuleNotFoundError:does not take it (a subclass does not take its base), a clause whose body raises on every path (raise) takes nothing, and a clause that certainly matches hides the clauses after it. A handler taking theModuleNotFoundErrorof a module a project package lacks lets the module body go on past that import. - Not a submodule: the project has no module
M.name(Python falls back to a submodule of that name once it is loaded), andnameis not a dunder the import system sets (__name__,__path__). - Not bound yet: before the import
Mis paused at,M's body has no statement that may bindname(an assignment, a definition, an import, also on a branch), binds no__getattr__, which afromimport falls back to, and runs no star import;Mhas noexec, no change throughglobals(), novars()orlocals()in its body, and no function or class body bindingnameunderglobal. - Not bound elsewhere: no other module of the project stores into or deletes
M.name, by name or withsetattrunder a name heki cannot read. - Nothing else loads the cycle: nothing that runs before the statement may load a module of the cycle out of the order shown. An import heki cannot place there (on a branch, behind a handler, lazy) of a module of the cycle that has not loaded yet, an import of a module heki cannot name, and a module outside the cycle whose own load may load one of the cycle stop the run. When some function or lazy import of the project may load a module of the cycle, so does any code that runs before the statement other than imports and stores of names (a call, a class statement, a decorator, an operator, an attribute or item access): it may call that function.
A report says which module, imported first, fails: importing another module of the cycle first may load them in an order that works.
Why is this bad?¶
A package whose modules import names from each other works only while it is imported through
the module that loads them in a working order. Importing another of its modules first, as a
test, a script, a plugin loader, or a user of the library may do, fails with an ImportError
that names a module that exists and a name it defines. The failure depends on the order modules
are imported in, so it can appear only in one environment or one test run. A type checker, which
reads the names a module defines but not the order statements run in, does not see it.
Example¶
# pkg/a.py
from pkg.b import helper_b # IMP102 when `pkg.b` is imported first
def helper_a() -> int:
return helper_b() + 1
# pkg/b.py
from pkg.a import helper_a # IMP102 when `pkg.a` is imported first
def helper_b() -> int:
return 1
def uses_a() -> int:
return helper_a()
Importing pkg.a first runs pkg/a.py, which imports pkg.b before it defines helper_a;
pkg/b.py then asks pkg.a for helper_a, which it has not bound yet.
Use instead:
# pkg/b.py
def helper_b() -> int:
return 1
def uses_a() -> int:
from pkg.a import helper_a
return helper_a()
Fix safety¶
No automatic fix.
Options¶
- Its reports are errors:
lint.severity = { IMP102 = "warning" }makes them warnings.
Known limitations¶
- Imports heki does not see (
exec,runpy, a module loaded from a file path, an import a library function makes, such as a plugin manager loading entry points) are not followed, and neither is a write tosys.modulesor a module object given another class. - A run stops, and reports nothing from that point on, at the first code that may load a module
of the cycle out of order. An import under
if __name__ == "__main__":, which never runs when the module is imported, counts as an import on a branch.