Undeclared options (**kwargs)¶
Typer only accepts the options you declare. With command, a function that takes
**kwargs also receives any --key value option you did not declare.
import typer
from typer_swissknife import command
app = typer.Typer()
@command(app)
def some_command(name: str, **options: int) -> None:
print(name, options)
@command(app)
def other() -> None: ...
$ python app.py some-command Abdullah --num1 10 --num2 20
Abdullah {'num1': 10, 'num2': 20}
$ python app.py some-command Abdullah --num1=10 --page-size=50
Abdullah {'num1': 10, 'page_size': 50}
$ python app.py some-command --num1 10 Abdullah
Abdullah {'num1': 10}
$ python app.py some-command Abdullah --num1 abc
Usage: app.py some-command [OPTIONS] NAME
Try 'app.py some-command --help' for help.
┌─ Error ─────────────────────────────────────────────┐
│ Invalid value for --num1: 'abc' is not a valid int. │
└─────────────────────────────────────────────────────┘
The rules¶
- Both
--key valueand--key=valuework, and can be mixed. - Undeclared options can go before, between or after the arguments.
- Dashes in the name become underscores:
--page-sizegivespage_size. - A repeated option keeps its last value.
- Only long options (
--key) are collected.-xis an error.
The full syntax, including every error, is in Undeclared option syntax.
Value types¶
Each value is converted with the annotation of **kwargs:
| Annotation | --x 5 gives |
Notes |
|---|---|---|
none, str or Any |
"5" |
values stay strings |
int |
5 |
negative numbers work: --dx -5 |
float |
5.0 |
|
bool |
1 true t yes y on / 0 false f no n off, any case |
|
an Enum |
Color("5") |
converted by value |
any callable, such as Path or your own function |
Path("5") |
annotation(value) |
A value the annotation rejects with ValueError or TypeError exits with a usage error
such as Invalid value for --num1: 'abc' is not a valid int.
Other exceptions are not caught
Only ValueError and TypeError become usage errors. Decimal("abc") raises
decimal.InvalidOperation, which surfaces as a traceback; wrap such types in a
converter that raises ValueError, as in the
invoice recipe.
from pathlib import Path
@command(app)
def export(**paths: Path) -> None:
for name, path in paths.items():
print(name, path.suffix)
Mixing with declared parameters¶
Declared arguments and options work as usual, alongside the undeclared ones:
@command(app)
def deploy(
env: str,
replicas: int = typer.Option(1, "--replicas", "-r"),
force: bool = typer.Option(False, "--force/--no-force"),
**labels: str,
) -> None:
print(env, replicas, force, labels)
An undeclared option with the same name as a declared parameter is an error
(Option --env clashes with a declared parameter), so **kwargs never silently
overrides an argument.
What else to know¶
- Undeclared options are not listed in
--help; document them in the help text. - Other commands of the same app are not affected: they still reject unknown options.
- Aliases and
ascii_namework together with**kwargs. - Your own
context_settingswin. Passingcontext_settings={"ignore_unknown_options": False}turns the feature back off for that command. no_args_is_help=Truedoes not trigger when only undeclared options are given.- A custom
clsis kept;commandsubclasses it to reorder the arguments. - The function is returned unchanged, so you can still call it with keyword arguments:
export(out=Path("a.txt")).
With typer-di¶
Apps built with typer-di's TyperDI work too.
Options declared by Depends(...) dependencies are resolved by typer-di, listed in
--help, and not collected into **kwargs.
from typing import Annotated
import typer
from typer_di import Depends, TyperDI
from typer_swissknife import command
app = TyperDI()
def get_user(user: str = typer.Option("guest", "--user", "-u")) -> str:
return user.upper()
@command(app, aliases=("g",))
def greet(name: str, user: Annotated[str, Depends(get_user)], **numbers: int) -> None:
print(name, user, numbers)
@command(app)
def other() -> None: ...