Command Help
The same as before, you can add help for the commands in the docstrings and the CLI options.
And the typer.Typer()
application receives a parameter help
that you can pass with the main help text for your CLI program:
import typer_cloup as typer
app = typer.Typer(help="Awesome CLI user manager.")
@app.command()
def create(username: str):
"""
Create a new user with USERNAME.
"""
typer.echo(f"Creating user: {username}")
@app.command()
def delete(
username: str,
force: bool = typer.Option(
...,
prompt="Are you sure you want to delete the user?",
help="Force deletion without confirmation.",
),
):
"""
Delete a user with USERNAME.
If --force is not used, will ask for confirmation.
"""
if force:
typer.echo(f"Deleting user: {username}")
else:
typer.echo("Operation cancelled")
@app.command()
def delete_all(
force: bool = typer.Option(
...,
prompt="Are you sure you want to delete ALL users?",
help="Force deletion without confirmation.",
)
):
"""
Delete ALL users in the database.
If --force is not used, will ask for confirmation.
"""
if force:
typer.echo("Deleting all users")
else:
typer.echo("Operation cancelled")
@app.command()
def init():
"""
Initialize the users database.
"""
typer.echo("Initializing user database")
if __name__ == "__main__":
app()
Check it:
Tip
typer.Typer()
receives several other parameters for other things, we'll see that later.
You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.
Overwrite command helpΒΆ
You will probably be better adding the help text as a docstring to your functions, but if for some reason you wanted to overwrite it, you can use the help
function argument passed to @app.command()
:
import typer_cloup as typer
app = typer.Typer()
@app.command(help="Create a new user with USERNAME.")
def create(username: str):
"""
Some internal utility function to create.
"""
typer.echo(f"Creating user: {username}")
@app.command(help="Delete a user with USERNAME.")
def delete(username: str):
"""
Some internal utility function to delete.
"""
typer.echo(f"Deleting user: {username}")
if __name__ == "__main__":
app()
Check it:
Deprecate a CommandΒΆ
There could be cases where you have a command in your app that you need to deprecate, so that your users stop using it, even while it's still supported for a while.
You can mark it with the parameter deprecated=True
:
import typer_cloup as typer
app = typer.Typer()
@app.command()
def create(username: str):
"""
Create a user.
"""
print(f"Creating user: {username}")
@app.command(deprecated=True)
def delete(username: str):
"""
Delete a user.
This is deprecated and will stop being supported soon.
"""
print(f"Deleting user: {username}")
if __name__ == "__main__":
app()
And when you show the --help
option you will see it's marked as "deprecated
":
And if you check the --help
for the deprecated command (in this example, the command delete
), it also shows it as deprecated: