[Python] Dynamically add subcommands in typer

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    In a typer command line interface with subcommands, is it possible to dynamically (during run time) change the subcommands and parameters that those take?

    Consider the following script as an example:

    import typer
    from typing import Annotated, Optional

    local_users_app = typer.Typer()
    @local_users_app.command("define")
    def local_define(address : Annotated[str, typer.Argument()]):
    print("local define")

    remote_users_app = typer.Typer()
    @remote_users_app.command("define")
    def remote_define(url: Annotated[str, typer.Argument()],
    platform: Annotated[str, typer.Argument()]):
    print("remote define")

    def user_callback(ctx: typer.Context,
    username : Annotated[str, typer.Argument()]):
    typer.echo(f"user name: {username}")

    # if is_local(username):
    # use local commands and interface
    # else:
    # use remote commands and interface

    app = typer.Typer()
    users_app = typer.Typer(callback=user_callback)
    app.add_typer(users_app, name="user")

    @users_app.command()
    def define():
    print(" ! define")
    pass

    if __name__=="__main__":
    app()


    That I would like to call with the following parameters:

    user local_user define address "an address"

    or

    user remote_user define url some_url platform some_platform

    So in this (artificial) example, I have a user command that has a callback which queries the user name. The app is able to determine whether it is a remote or a local user, so I don't want to specify this explicitly. Then I want to typer to query and parse the following parameters based on which user type the given user is.

    In a more general view, this is an example that occurs if I have derived classes (remote_user, local_user, derived from user) that I would like to be able to configure/initialize/use with their respective parameter set.

    Can that be done and if so, how?

    If this cannot be done, are there alternative ways to get a clean command-line interface?

    Continue reading...

Compartilhe esta Página