Commands and aliases¶
command(app, ...) is a decorator factory that works like @app.command(), with three
extras: aliases, ascii_name / ascii_font, and support for **kwargs.
A plain command¶
import typer
from typer_swissknife import command
app = typer.Typer()
@command(app)
def show_users() -> None:
"""Show all users."""
print("alice, bob")
@command(app, name="add")
def add_user(name: str) -> None:
print(f"Added {name}")
- The name defaults to the function name in kebab case:
show-users. name="add"overrides it.- The help defaults to the docstring, as in Typer.
The decorator returns the function unchanged, so add_user("alice") still works in
your own code and tests.
Aliases¶
import typer
from typer_swissknife import command
app = typer.Typer()
@command(app, name="list", aliases=("ls", "l"))
def list_users() -> None:
"""List all users."""
print("alice, bob")
@command(app, aliases="rm")
def remove(user: str) -> None:
"""Remove a user."""
print(f"Removed {user}")
$ python app.py ls
alice, bob
$ python app.py rm alice
Removed alice
$ python app.py --help
...
│ list (ls, l) List all users. │
│ remove (rm) Remove a user. │
How it works:
list,lsandlare each registered as a hidden command with the same function and settings.- One more, visible command named
list (ls, l)is registered for the help output. aliasesaccepts any iterable of strings: a tuple, a list, a generator. A single string is one alias (aliases="rm"), not a sequence of letters.- Duplicates and an alias equal to the command name are dropped.
- An empty or whitespace-only alias raises
ValueErrorat decoration time. aliases=()oraliases=Noneregisters a plain command, exactly like@app.command().
Hiding a command with aliases¶
hidden=True hides the visible entry. The name and aliases are always hidden, so the
command disappears from the help but every name still runs it.
Typer settings¶
All the other parameters of app.command() are passed through: cls,
context_settings, help, epilog, short_help, options_metavar,
add_help_option, no_args_is_help, hidden, deprecated and rich_help_panel.
@command(
app,
aliases=("st",),
help="Show the service status.",
rich_help_panel="Monitoring",
deprecated=True,
)
def status() -> None:
print("ok")
A banner on the help page¶
@command(app, name="list", aliases=("ls",), ascii_name="Users")
def list_users() -> None:
"""List all users."""
python app.py list --help (or ls --help) now starts with USERS drawn in the
ansi_shadow font, followed by "List all users.". See ASCII-art banners.
Undeclared options¶
When the function takes **kwargs, command also collects options you did not declare.
See Undeclared options.