NumberΒΆ
You can define numeric validations with max
and min
values for int
and float
CLI parameters:
import typer
from typing_extensions import Annotated
def main(
id: Annotated[int, typer.Argument(min=0, max=1000)],
age: Annotated[int, typer.Option(min=18)] = 20,
score: Annotated[float, typer.Option(max=100)] = 0,
):
print(f"ID is {id}")
print(f"--age is {age}")
print(f"--score is {score}")
if __name__ == "__main__":
typer.run(main)
π€ Other versions and variants
Tip
Prefer to use the Annotated
version if possible.
import typer
def main(
id: int = typer.Argument(..., min=0, max=1000),
age: int = typer.Option(20, min=18),
score: float = typer.Option(0, max=100),
):
print(f"ID is {id}")
print(f"--age is {age}")
print(f"--score is {score}")
if __name__ == "__main__":
typer.run(main)
CLI arguments and CLI options can both use these validations.
You can specify min
, max
or both.
Check it:
Clamping numbersΒΆ
You might want to, instead of showing an error, use the closest minimum or maximum valid values.
You can do it with the clamp
parameter:
import typer
from typing_extensions import Annotated
def main(
id: Annotated[int, typer.Argument(min=0, max=1000)],
rank: Annotated[int, typer.Option(max=10, clamp=True)] = 0,
score: Annotated[float, typer.Option(min=0, max=100, clamp=True)] = 0,
):
print(f"ID is {id}")
print(f"--rank is {rank}")
print(f"--score is {score}")
if __name__ == "__main__":
typer.run(main)
π€ Other versions and variants
Tip
Prefer to use the Annotated
version if possible.
import typer
def main(
id: int = typer.Argument(..., min=0, max=1000),
rank: int = typer.Option(0, max=10, clamp=True),
score: float = typer.Option(0, min=0, max=100, clamp=True),
):
print(f"ID is {id}")
print(f"--rank is {rank}")
print(f"--score is {score}")
if __name__ == "__main__":
typer.run(main)
And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:
Counter CLI optionsΒΆ
You can make a CLI option work as a counter with the counter
parameter:
import typer
from typing_extensions import Annotated
def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):
print(f"Verbose level is {verbose}")
if __name__ == "__main__":
typer.run(main)
π€ Other versions and variants
Tip
Prefer to use the Annotated
version if possible.
import typer
def main(verbose: int = typer.Option(0, "--verbose", "-v", count=True)):
print(f"Verbose level is {verbose}")
if __name__ == "__main__":
typer.run(main)
It means that the CLI option will be like a boolean flag, e.g. --verbose
.
And the value you receive in the function will be the amount of times that --verbose
was added: