Skip to content
Advertisement

How to resolve mutual dependencies between a main script and submodules needing access to a global variable from the script?

I’m building a Typer app with lots of commands. I want to categorize the commands into subfiles but am unsure how to resolve the dependencies.

JavaScript

main.py is the parent. It looks like this:

JavaScript

So, we make a new Typer app and import everything from the submodules. Simple enough.

Each of the submodules contains Typer commands, like booklist:

JavaScript

Here’s the problem: in order to define a Typer command with the @app.command() decorator, each submodule first needs to import app from the parent main.py. However, main.py gets run in the import statement for any of the submodules, and so a circular import arises when main.py imports whatever submodule it’s in.

How should one structure this project so that all submodules have access to app and main.py can also access all the submodules?

Advertisement

Answer

You could just have app be initialized in its own separate module. Let the sub-modules import it from there and have your main module import those sub-modules.

Something like this: app.py

JavaScript

booklist.py

JavaScript

main.py

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement