pydantic kwargs的类型提示?
from typing import Any
from datetime import datetime
from pydantic import BaseModel
class Model(BaseModel):
timestamp: datetime
number: int
name: str
def construct(dictionary: Any) -> Model:
return Model(**dictionary)
construct({"timestamp": "2024-03-14T10:00:00Z", "number": 7, "name":"Model"})
Argument 1 to "Model" has incompatible type "**dict[str, str]"; expected "datetime"
Argument 1 to "Model" has incompatible type "**dict[str, str]"; expected "number"
Argument 1 to "Model" has incompatible type "**dict[str, str]"; expected "name"
在construct
里用什么类型提示代替Any
呢?
比如说,如果我把dict[str, str]
作为类型放进去,我会得到错误。
1 个回答
1
def construct(dictionary: dict[str, Any]) -> Model:
return Model(**dictionary)
def construct(dictionary: dict[str, Union[str, int]]) -> Model:
return Model.model_validate(dictionary)
或者,你可以用 Union
来声明更具体的类型,然后使用 model_validate
方法来验证输入的数据,而不是用模型的构造函数。