Type hint for pydantic kwargs?

34 views Asked by At
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"})

What is the type hint to use in construct instead of Any?

If, for example, I put dict[str, str] as the type I get the errors

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"
1

There are 1 answers

0
Yurii Motov On BEST ANSWER
def construct(dictionary: dict[str, Any]) -> Model:
    return Model(**dictionary)

Or, you can declare more specific type with Union and use model_validate method instead of model's constructor to validate input data:

def construct(dictionary: dict[str, Union[str, int]]) -> Model:
    return Model.model_validate(dictionary)