跳至内容

自定义类型

您可以在 Typer 应用程序中轻松使用自己的自定义类型。

实现方法是提供一种方法来 解析 输入到您自己的类型。

有两种方法可以实现这一点

  • 添加类型 解析器
  • 扩展 Click 的自定义类型

类型解析器

typer.Argumenttyper.Option 可以使用 解析器 可调用对象 创建自定义参数类型。

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)

提示

如果可能,请优先使用 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)


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)

传递给参数 parser 的函数(或可调用对象)将接收输入值作为字符串,并应返回使用您自己的自定义类型解析后的值。

点击自定义类型

如果您已经拥有 Click 自定义类型,您可以在 typer.Argument()typer.Option() 中使用 click_type 参数。

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)

提示

如果可能,请优先使用 Annotated 版本。

import click
import typer


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: CustomClass = typer.Argument(click_type=CustomClassParser()),
    custom_opt: CustomClass = typer.Option("Foo", click_type=CustomClassParser()),
):
    print(f"custom_arg is {custom_arg}")
    print(f"--custom-opt is {custom_opt}")


if __name__ == "__main__":
    typer.run(main)