静态类型检查器(mypy、pytype、pyright)抱怨动态生成的`Union`

问题描述 投票:0回答:1

如何从动态

Union
创建 TypeAdapter 而不会遇到 linting 错误?

from pydantic import BaseModel, TypeAdapter

class Lion(BaseModel):
    roar: str


class Tiger(BaseModel):
    roar: str


ZOO = {
    "lion": Lion,
    "tiger": Tiger,
    # ...
}

Animal = Union[*[animal for animal in ZOO.values()]]    # Error: Invalid type alias: expression is not a valid type

AnimalTypeAdapter: TypeAdapter[Animal] = TypeAdapter(Animal)    # Error: Variable "Animal" is not valid as a type

python python-typing mypy pydantic
1个回答
0
投票

你不能。

您应该首先定义联合,然后将其转换回运行时结构:

from typing import Union, get_args

Animal = Union[Tiger, Lion]

ZOO = dict(zip(['tiger', 'lion'], get_args(Animal)))
# {'tiger': Tiger, 'lion': Lion}
© www.soinside.com 2019 - 2024. All rights reserved.