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.
Type Parser¶
typer.Argument and typer.Option can create custom parameter types with a parser callable.
from typing import Annotated
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)
app = typer.Typer()
@app.command()
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__":
app()
🤓 Other versions and variants
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)
app = typer.Typer()
@app.command()
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__":
app()
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.