From 17c094460f5638f87f725e52d3bda5a7210d711a Mon Sep 17 00:00:00 2001 From: Charles Duffy Date: Tue, 29 Oct 2024 16:00:52 -0500 Subject: [PATCH] fix(Pydantic): For type-checker purposes, have a pydantic_v2_mandatory that cannot be None --- litestar/contrib/pydantic/pydantic_init_plugin.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/litestar/contrib/pydantic/pydantic_init_plugin.py b/litestar/contrib/pydantic/pydantic_init_plugin.py index e8623d7809..4c9ff701dc 100644 --- a/litestar/contrib/pydantic/pydantic_init_plugin.py +++ b/litestar/contrib/pydantic/pydantic_init_plugin.py @@ -33,8 +33,12 @@ if TYPE_CHECKING: + import pydantic as pydantic_v2_mandatory + from litestar.config.app import AppConfig from litestar.types.serialization import PydanticV1FieldsListType, PydanticV2FieldsListType +else: + pydantic_v2_mandatory = pydantic_v2 T = TypeVar("T") @@ -47,13 +51,13 @@ def _dec_pydantic_v1(model_type: type[pydantic_v1.BaseModel], value: Any) -> pyd raise ExtendedMsgSpecValidationError(errors=cast("list[dict[str, Any]]", e.errors())) from e -def _dec_pydantic_v2(model_type: type[pydantic_v2.BaseModel], value: Any, strict: bool) -> pydantic_v2.BaseModel: # pyright: ignore[reportInvalidTypeForm] +def _dec_pydantic_v2( + model_type: type[pydantic_v2_mandatory.BaseModel], value: Any, strict: bool +) -> pydantic_v2.BaseModel: # pyright: ignore[reportInvalidTypeForm] try: return model_type.model_validate(value, strict=strict) - except pydantic_v2.ValidationError as e: - hide_input = False - if isinstance(model_config := getattr(model_type, "model_config", None), dict): - hide_input = bool(model_config.get("hide_input_in_errors")) + except pydantic_v2_mandatory.ValidationError as e: + hide_input = model_type.model_config.get("hide_input_in_errors", False) raise ExtendedMsgSpecValidationError( errors=cast("list[dict[str, Any]]", e.errors(include_input=not hide_input)) ) from e