Typer
Behind the scenes, Jeeves relies upon Typer.
Every function in jeeves.py
is converted into a Typer command. Just as if you did:
from typer import Typer
app = Typer()
@app.command()
def hi(name: str):
"""…"""
if __name__ == '__main__':
app()
- That's one way how Jeeves reduces the boilerplate;
- The other way is to expose all those commands via the
j
shortcut.
Nonetheless, you still can use most Typer features, such as:
- define
typer.Argument
's andtyper.Option
's for your commands, - validate user input using type hints,
- and much more.
Example: Use Typer features directly
jeeves.py
from enum import Enum, auto
import typer
class GreetingStyle(Enum):
"""Style of the greeting."""
ENGLISH = 'en'
ITALIAN = 'it'
def hi(
name: str = typer.Argument(
...,
help='Name of the one we would like to greet.',
envvar='NAME_TO_GREET',
),
style: GreetingStyle = typer.Option(
GreetingStyle.ENGLISH,
help='Style of the greeting.',
),
):
"""Greet the user."""
greeting = {
GreetingStyle.ENGLISH: 'Hello',
GreetingStyle.ITALIAN: 'Buongiorno',
}[style]
typer.echo(f'{greeting} {name}!')
⇒
↦
j hi --help
Usage: j hi [OPTIONS] NAME
Greet the user.
╭─ Arguments ──────────────────────────────────────────────────────────────────╮
│ * name TEXT Name of the one we would like to greet. │
│ [env var: NAME_TO_GREET] │
│ [default: None] │
│ [required] │
╰──────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────╮
│ --style [en|it] Style of the greeting. │
│ [default: GreetingStyle.ENGLISH] │
│ --help Show this message and exit. │
╰──────────────────────────────────────────────────────────────────────────────╯
Example: Typer Validation
↦
j hi --style de
(stdout is empty)
Error
Usage: j hi [OPTIONS] NAME
Try 'j hi --help' for help.
╭─ Error ──────────────────────────────────────────────────────────────────────╮
│ Invalid value for '--style': 'de' is not one of 'en', 'it'. │
╰──────────────────────────────────────────────────────────────────────────────╯