pydantic kwargs的类型提示?

0 投票
1 回答
28 浏览
提问于 2025-04-14 16:09
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 方法来验证输入的数据,而不是用模型的构造函数。

撰写回答