CodeQL documentation

Module-level cyclic import

ID: py/unsafe-cyclic-import
Kind: problem
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
   - types
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

A cyclic import is an import which imports another module and that module imports (possibly indirectly) the module which contains the import statement. If all imports in a cyclic import occur at module level, then a module will be imported when it is part way through its initialization. This may rest in surprising errors, as parts of the module being imported may not yet exist.

In addition to the possible errors, cyclic imports indicate that two modules are circularly dependent. This means that the modules cannot be tested independently, and it makes it harder to understand the architecture of the system.

Recommendation

The cycle may be broken by removing any one import. If only one function or method requires the import, then consider moving that to the other module and deleting the import. If the two modules are more intimately connected, then move the inter-dependent parts into a third module and have both the original modules import that.

References