Custom Types¶
You can easily use your own custom types in your Typer applications.
The way to do it is by providing a way to parse input into your own types.
There are two ways to achieve this:
- Adding a type
parser
- Expanding Click's custom types
Type Parser¶
typer.Argument
and typer.Option
can create custom parameter types with a parser
callable.
import typer
from typing_extensions import Annotated
class CustomClass:
def __init__(self, value: str):
self.value = value
def __str__(self):
return f"<CustomClass: value={self.value}>"
def parse_custom_class(value: str):
return CustomClass(value * 2)
def main(
custom_arg: Annotated[CustomClass, typer.Argument(parser=parse_custom_class)],
custom_opt: Annotated[CustomClass, typer.Option(parser=parse_custom_class)] = "Foo",
):
print(f"custom_arg is {custom_arg}")
print(f"--custom-opt is {custom_opt}")
if __name__ == "__main__":
typer.run(main)
Tip
Prefer to use the Annotated
version if possible.
import typer
class CustomClass:
def __init__(self, value: str):
self.value = value
def __str__(self):
return f"<CustomClass: value={self.value}>"
def parse_custom_class(value: str):
return CustomClass(value * 2)
def main(
custom_arg: CustomClass = typer.Argument(parser=parse_custom_class),
custom_opt: CustomClass = typer.Option("Foo", parser=parse_custom_class),
):
print(f"custom_arg is {custom_arg}")
print(f"--custom-opt is {custom_opt}")
if __name__ == "__main__":
typer.run(main)
The function (or callable) that you pass to the parameter parser
will receive the input value as a string and should return the parsed value with your own custom type.
Click Custom Type¶
If you already have a Click Custom Type, you can use it in typer.Argument()
and typer.Option()
with the click_type
parameter.
import click
import typer
from typing_extensions import Annotated
class CustomClass:
def __init__(self, value: str):
self.value = value
def __repr__(self):
return f"<CustomClass: value={self.value}>"
class CustomClassParser(click.ParamType):
name = "CustomClass"
def convert(self, value, param, ctx):
return CustomClass(value * 3)
def main(
custom_arg: Annotated[CustomClass, typer.Argument(click_type=CustomClassParser())],
custom_opt: Annotated[
CustomClass, typer.Option(click_type=CustomClassParser())
] = "Foo",
):
print(f"custom_arg is {custom_arg}")
print(f"--custom-opt is {custom_opt}")
if __name__ == "__main__":
typer.run(main)