Calmcode - typer: options

Options

1 2 3 4 5 6 7 8 9 10

The relationship between arguments and keyword-arguments in python is similar to the relation ship between arguments and options in typer. If you're unfamiliar between the difference between arguments and keyword arguments then you might appreciate our course on args and kwargs

The main thing to remember is that the order for arguments really matters. That's the main difference between an option and an argument. Arguments are determined by the order they are passed while options have a specific name attached and the other no longer matters.

Example with Typer Options and Typer Arguments

import typer
from typing import List
from pathlib import Path

app = typer.Typer(name="demo", add_completion=False, help="This is a demo app.")

@app.command()
def talk(text: str = typer.Argument(..., help="The text to type."),
         repeat: int = typer.Option(1, help="Number of times to repeat."),
         loud: bool = typer.Option(False, is_flag=True)):
    """Talks some text below"""
    if loud:
        text = text.upper()
    for _ in range(repeat):
        print(text)


if __name__ == "__main__":
    app()

The talk command can be run in multiple ways now.

python cli.py talk "hello there"
python cli.py talk "hello there" --repeat 2
python cli.py talk "hello there" --loud
python cli.py talk "hello there" --loud --repeat 3

Note that the --loud option is considered a flag.