python programming circular reference

Python: simple tricks to prevent circular import issues

Example of a circular import error

Example of a circular reference error

Example of a circular reference error

What constitutes a circular import in programming?

This occurs when a file named a.py imports elements from a file named b.py which in turn imports elements from a.py.

Illustration by the author.

Illustration by the author.

A module cannot function if it isn’t completely loaded first. In other words, all the modules that this one imports must also be fully loaded beforehand.

In our situation, it is analogous to a snake biting its own tail.

How can we prevent it?

It is preferable to use the “quote notation” when typing a hint for a variable.

…and as much as possible, perform imports only when TYPE_CHECKING is set to True (in other words, not during program execution).

The use of “quote notation” prevents the program from crashing at runtime due to the unloaded referenced type.

By employing the if TYPE_CHECKING condition, you can import a module specifically for Integrated Development Environment (IDE) autocompletion features. However, at runtime, TYPE_CHECKING will invariably be set to False so no circular import here.

Illustration by the author.

Illustration by the author.

Use the ‘lazy’ module import feature when it is required.

You may not be aware that you are not obliged to carry out all your imports at the highest level of your module. Instead, you have the flexibility to import other modules within your methods or functions. So it won’t cause a circular reference neither.

Illustration by the author. The "real" import of module a is only done inside the create_a method

Illustration by the author. The “real” import of module a is only done inside the create_a method

By employing both these tricks, you should be able to resolve any circular reference predicaments that may arise while working in your Python project.

That’s all folks!