Skip to content

Instantly share code, notes, and snippets.

@blakeNaccarato
Last active January 13, 2024 01:15
Show Gist options
  • Save blakeNaccarato/0e3719bf9fe93ea4e45c5868a7eb94d1 to your computer and use it in GitHub Desktop.
Save blakeNaccarato/0e3719bf9fe93ea4e45c5868a7eb94d1 to your computer and use it in GitHub Desktop.
How to flatten nested namespaces when creating a Typer CLI.

__main__.py

How to flatten nested namespaces when creating a Typer CLI.

"""CLI for boilerdata."""
from types import ModuleType
from typer import Typer
from typer.main import get_command_name
def add_typer_autoname(app: Typer, module: ModuleType):
"""Add a subcommand to a Typer app, inferring its name from the module name.
Given a Typer app and a module, add a subcommand to the Typer app with the same name
as the module itself, all lowercase and with underscores swapped for dashes. This
flattens nested namespaces.
Parameters
----------
app: Typer
The app to which a subcommand should be added.
module: ModuleType
The module which will be added as an automatically-named subcommand.
"""
name = get_command_name(module.__name__.split(".")[-1])
app.add_typer(module.app, name=name)
app = Typer()
for module in []:
add_typer_autoname(app, module)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment