How can I organize a small program into modules without circular imports?
Quick answer
Map which modules import one another and look for a path that leads back to its starting point. If two modules need the same small function or constant, consider moving it into a third, lower-level module that neither depends on the other. Otherwise, remove unnecessary imports or narrow them to what is needed. Python initializes modules during import, so mutual imports during initialization can encounter a module that is not fully initialized. Check the revised import flow in your program; these patterns are not guaranteed fixes. [S1]
The question, the details, the next step.
A practical checklist
List each module's imports, including imports in package
__init__.pyfiles.Trace import paths and mark any route that returns to its starting module.
Remove imports that are not needed; narrow imports to the required name or module.
Move only genuinely shared, lower-level functions or data into a third module.
Check that the shared module does not import back into its users.
Check the revised import flow using the program's usual entry point and environment.
A few more useful answers
Does importing a specific name instead of a whole module always prevent a circular import?
No. It can clarify or narrow a dependency, but mutual imports during module initialization can still create a cycle. Check the full import path and actual initialization behavior. [S1]
Should every function used by two modules go into a shared utilities file?
No. Move code only when it is genuinely shared and fits a lower-level module. A catch-all file can obscure responsibilities rather than clarify them.
Sources
References used for this guide.
- [S1] Python 3.15 import system reference: packages and module loading docs.python.org · Checked
