Multiple CLI Options
You can declare a CLI option that can be used multiple times, and then get all the values.
For example, let's say you want to accept several users in a single execution.
For this, use the standard Python typing.List
to declare it as a list
of str
:
from typing import List, Optional
import typer
from typing_extensions import Annotated
def main(user: Annotated[Optional[List[str]], typer.Option()] = None):
if not user:
print(f"No provided users (raw input = {user})")
raise typer.Abort()
for u in user:
print(f"Processing user: {u}")
if __name__ == "__main__":
typer.run(main)
Tip
Prefer to use the Annotated
version if possible.
from typing import List, Optional
import typer
def main(user: Optional[List[str]] = typer.Option(None)):
if not user:
print(f"No provided users (raw input = {user})")
raise typer.Abort()
for u in user:
print(f"Processing user: {u}")
if __name__ == "__main__":
typer.run(main)
You will receive the values as you declared them, as a list
of str
.
Check it:
Multiple float
ΒΆ
The same way, you can use other types and they will be converted by Typer to their declared type:
from typing import List
import typer
from typing_extensions import Annotated
def main(number: Annotated[List[float], typer.Option()] = []):
print(f"The sum is {sum(number)}")
if __name__ == "__main__":
typer.run(main)
Tip
Prefer to use the Annotated
version if possible.
from typing import List
import typer
def main(number: List[float] = typer.Option([])):
print(f"The sum is {sum(number)}")
if __name__ == "__main__":
typer.run(main)
Check it: