Optional value for CLI Options¶
As in Click, providing a value to a CLI option can be made optional, in which case a default value will be used instead.
To make a CLI option's value optional, you can annotate it as a Union of types bool and the parameter type.
Info
You can create a type Union by importing Union from the typing module.
For example Union[bool, str]
represents a type that is either a boolean or a string.
You can also use the equivalent notation bool | str
Let's add a CLI option --tone
with optional value:
import typer
from typing_extensions import Annotated
def main(
name: str, lastname: str, greeting: Annotated[bool | str, typer.Option()] = "formal"
):
if not greeting:
return
if greeting == "formal":
print(f"Hello {name} {lastname}")
elif greeting == "casual":
print(f"Hi {name} !")
else:
raise ValueError(f"Invalid greeting '{greeting}'")
if __name__ == "__main__":
typer.run(main)
š¤ Other versions and variants
Tip
Prefer to use the Annotated
version if possible.
import typer
def main(name: str, lastname: str, greeting: bool | str = "formal"):
if not greeting:
return
if greeting == "formal":
print(f"Hello {name} {lastname}")
elif greeting == "casual":
print(f"Hi {name} !")
else:
raise ValueError(f"Invalid greeting '{greeting}'")
if __name__ == "__main__":
typer.run(main)
Now, there are three possible configurations:
-
--greeting
is not used, the parameter will receive a value ofFalse
.python main.py
-
--greeting
is supplied with a value, the parameter will receive the string representation of that value.python main.py --greeting <value>
-
--greeting
is used with no value, the parameter will receive the defaultformal
value.python main.py --greeting
And test it:
$ python main.py Camila GutiƩrrez
// We didn't pass the greeting CLI option, we get no greeting
// Now update it to pass the --greeting CLI option with default value
$ python main.py Camila GutiƩrrez --greeting
Hello Camila GutiƩrrez
// The above is equivalent to passing the --greeting CLI option with value `formal`
$ python main.py Camila GutiƩrrez --greeting formal
Hello Camila GutiƩrrez
// But you can select another value
$ python main.py Camila GutiƩrrez --greeting casual
Hi Camila !