typer icon indicating copy to clipboard operation
typer copied to clipboard

Unexpected behavior of no_args_is_help with 0 or 1 commands

Open jacob-bush-shopify opened this issue 2 years ago • 1 comments

First Check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the Typer documentation, with the integrated search.
  • [X] I already searched in Google "How to X in Typer" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to Typer but to Click.

Example Code

Example 1

I expect help when invoked with no args

import typer

cli = typer.Typer(no_args_is_help=True)

if __name__ == "__main__":
    cli()

Actually raises an exception

$ python cli.py
AssertionError: Could not get a command for this Typer instance

Example 2

I expect help when invoked with no args

import typer

cli = typer.Typer(no_args_is_help=True)

@cli.command("1") 
def _1():
    print(1)

if __name__ == "__main__":
    cli()

Actually prints "1"

$ python cli.py
1

Example 3

I expect help when invoked with no args

import typer

cli = typer.Typer(no_args_is_help=True)

@cli.command("1") 
def _1():
    print(1)

@cli.command("2") 
def _2():
    print(2)

if __name__ == "__main__":
    cli()

Works as expected (though this breaks code relying on the behaviour of the 1-command typer app)

$ python cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...

Options:
  --install-completion [bash|zsh|fish|powershell|pwsh]
                                  Install completion for the specified shell.
  --show-completion [bash|zsh|fish|powershell|pwsh]
                                  Show completion for the specified shell, to
                                  copy it or customize the installation.
  --help                          Show this message and exit.

Commands:
  1
  2

Description

When no_args_is_help=True is set on my Typer application, I expect that the application will print the help text when it is called with no arguments.

When 2+ commands are registered, no_args_is_help works as expected.

However, there are two cases where this does not hold:

  • When there are 0 commands registered on the application, an exception is raised
  • When there is 1 command registered on the application, the command is called in lieu of printing the help text.

Operating System

macOS

Typer Version

0.6.1

Python Version

3.9.12

jacob-bush-shopify avatar Sep 01 '22 15:09 jacob-bush-shopify

I solved this for myself with this gist.

marcstreeter avatar Sep 06 '23 13:09 marcstreeter