一个值满足联合类型的哪个部分?

1 投票
1 回答
39 浏览
提问于 2025-04-13 01:32

我正在使用 Typing 模块和 Pydantic 来定义一个自定义类型,这个类型是一个联合类型。请问我怎么能知道在初始化类之后,某个特定的值满足了联合类型中的哪一部分呢?

比如,在下面的代码中:

from datetime import datetime
from typing import Union, Literal, Tuple, List

from pydantic import BaseModel, UUID4, ValidationError


class ExportDataRequest(BaseModel):
    customers: Union[Literal["all"], List[UUID4], UUID4, List[int], int]
    daterange: Union[Tuple[datetime, datetime], int]


data = {
    "customers": "all",
    'daterange': ("2024-01-01", "2024-03-01")
}

try:
    model = ExportDataRequest(**data)
    
    print(type(model.customers))
    # str
except ValidationError as e:
    print(e.errors())

上面输入给 customers 的值所满足的 Union 类型是 Literal["all"] 这一部分。

如果我像上面的代码片段那样询问 model.customers 的类型,python 会回复 str

有没有办法确定它是来自我类定义的 Literal["all"] 呢?

1 个回答

1

对于看到这个的人,我用 Pydantic 的 TypeAdapter 解决了这个问题:https://docs.pydantic.dev/latest/concepts/type_adapter/

在上面问题的代码中添加以下内容:

from pydantic import TypeAdapter

def handle_type(model):
    types_to_check = [
        (Literal["all"], "all"),
        (List[UUID4], "uuid_list"),
        (List[int], "int_list"),
        (int, "int"),
        (UUID4, "uuid"),
    ]

    for type_to_check, result in types_to_check:
        try:
            TypeAdapter(type_to_check).validate_python(model.customers)
            return result
        except ValidationError:
            pass

    return None

撰写回答