CloudBytes.dev icon indicating copy to clipboard operation
CloudBytes.dev copied to clipboard

/99999976-python-typer-set-default-command.md does not work

Open boborbt opened this issue 11 months ago • 2 comments

Hi, I was trying to find a way to set a default command in typer and I encountered your post. You may be interested in the fact that the solution provided in /99999976-python-typer-set-default-command.md does not work does allow you to have one command to be executed without specifying the command name (good), but has the problem that it will be always executed. That is, if you just want to execute bar you cannot.

In your case, if you try to execute the bar command, one would expect to see just the ouput of the bar command i.e.,

I'm just here to mess things up...

while it currently outputs:

None, None, None
I'm just here to mess things up...

which is te combination of foo and bar.

BTW, if you happen to know how to solve this, I would love to learn it 😊

Best, Roberto

boborbt avatar Jan 22 '25 15:01 boborbt

while it currently outputs:

None, None, None
I'm just here to mess things up...

which is te combination of foo and bar.

BTW, if you happen to know how to solve this, I would love to learn it 😊

Best, Roberto

So I went in to a rabbit hole with this, and you're absolutely right. I suspect this is a recent updated because when the article was written I didn't face this issue.

However, the solution / workaround is: that you can use type.Context to verify if no subcommands are executed and only then execute the default command.

import typer

app = typer.Typer(add_completion=False)


@app.callback(invoke_without_command=True)
def foo(ctx: typer.Context, lat: float = None, long: float = None, method: str = None):
    if ctx.invoked_subcommand is None:
        typer.echo(f"{lat}, {long}, {method}")


@app.command()
def bar():
    typer.echo("I'm just here to mess things up...")


if __name__ == "__main__":
    app()

It may have a better more elegant solution that I'm unaware of at the moment.

rehanhaider avatar Jan 28 '25 18:01 rehanhaider

@rehanhaider Update this article.

rehanhaider avatar Apr 04 '25 18:04 rehanhaider