'Python & Typer - Project structure and storing option values as an object
I currently have two interesting issues within a python package I am working on.
Considerations
I am using:
- Poetry
- Typer
- Python 3.8.12
Issue Summary
- Using Typer, I need to pass an input from an option from the CLI into another module for use as a configuration parameter
- I would need this to be passed before other upstream modules ran. I would also need to resolve the circular import that doing this would cause
Issue Diagram
Issue #1 details:
I have the following class and function within the main.py module
@dataclass
class Common:
profile_dir: str
@app.callback()
def profile_callback(ctx: typer.Context,
profile_dir: str = typer.Option(..., )):
typer.echo(f"Hello {profile_dir}")
test_dir = {profile_dir}
"""Common Entry Point"""
ctx.obj = Common(profile_dir)
return (test_dir)
The option works well when just echoing the CLI option but I have issues returning the {profile_dir} variable outside of the CLI. Typer only seems to be able to echo the variable, not store it. I am struggling to reference {profile_dir} outside of the CLI and outside the function.
What I would like to be able to do is turn {profile_dir} into an object that I can reference outside of the function and that I can pass from main.py into config.py
Issue #2
If I were to resolve issue #1, I would then encountered issue#2. As the CLI commands exist within the module_#_cli.py files and the main.py file, they import from the config.py upstream. This would lead me to the following error:
cannot import name 'cli_profile_path' from partially initialized module 'example.main' (most likely due to a circular import)
I'm pretty dumbfounded about how to resolve this as the package would import config parameters from the config.py module when there is no CLI option. I have struggled to think of a way to pass config parameters from the CLI into the config.py classes to then be used within the intermediary modules without the counterintuitive flow within the diagram.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

