如何从动态
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
你不能。
您应该首先定义联合,然后将其转换回运行时结构:
from typing import Union, get_args
Animal = Union[Tiger, Lion]
ZOO = dict(zip(['tiger', 'lion'], get_args(Animal)))
# {'tiger': Tiger, 'lion': Lion}