admin管理员组文章数量:1129108
How does one go about creating a TypeAdapter from a dynamic Union
without running into linting errors?
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
How does one go about creating a TypeAdapter from a dynamic Union
without running into linting errors?
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
Share
Improve this question
edited Jan 8 at 15:45
InSync
10.3k4 gold badges15 silver badges51 bronze badges
asked Jan 8 at 14:58
fmagnofmagno
1,54815 silver badges29 bronze badges
6
|
Show 1 more comment
1 Answer
Reset to default 3You can't.
You should instead define the union first, then convert that back to runtime structures:
from typing import Union, get_args
Animal = Union[Tiger, Lion]
ZOO = dict(zip(['tiger', 'lion'], get_args(Animal)))
# {'tiger': Tiger, 'lion': Lion}
本文标签:
版权声明:本文标题:python - Static type checker (mypy, pytype, pyright) complains with dynamically generated `Union` - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736714405a1949121.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
@dataclass
). Having to rely on external tools for codegen is definitely not what I expect from a modern language, and especially not from Python, which is perfectly capable (within limits) of integrated codegen. – Konrad Rudolph Commented Jan 8 at 21:44