How can I put typer commands in seperate modules without becoming sub-commands?

Viewed 32

Here is a fudge which works but causes problems with option position flexibility and help:

main.py:

import typer
import mycommand
app = typer.Typer()
app.add_typer(mycommand.app, name='mycommand')
@app.command()
def othercmd():
    pass
if __name__ == '__main__':
    app()

mycommand.py:

from typing import List
import typer
app = typer.Typer()
@app.callback(invoke_without_command=True)   # Not a sub command - run this by default
def mycommand(files: List[str] = typer.Argument(...), name: str = typer.Option(None)):
    if name: print(f'Hello {name}')
    print(files)

You can run this now with python main.py mycommand --name Butty myfile.txt. However, attempting to run with python main.py mycommand myfile.txt --name Butty will load the option into the files argument.

Issuing main.py mycommand --help reveals why; there is an extra command and args expected after the callback options and arguments:

Usage: main.py mycommand [OPTIONS] FILES... COMMAND [ARGS]...

Arguments:
  FILES...  [required]

Options:
  --name TEXT
  --help       Show this message and exit.

Is there a way to add a command to typer in a separate module as a "default" command which would react the same as using @app.command()?

0 Answers
Related