Search code examples
pythonpydanticpydantic-v2

Type hint for 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"})

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"

Solution

  • 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)