Feature: 放宽 pydantic compat model dump 类型 (#3898)

This commit is contained in:
呵呵です
2026-03-15 21:50:00 +08:00
committed by GitHub
parent 6090870244
commit 8f7aaf2b21
4 changed files with 58 additions and 16 deletions

View File

@@ -19,7 +19,9 @@ from typing import (
Generic,
Literal,
Protocol,
TypeAlias,
TypeVar,
cast,
get_args,
get_origin,
overload,
@@ -44,6 +46,16 @@ if TYPE_CHECKING:
CVC = TypeVar("CVC", bound=_CustomValidationClass)
ModelDumpIncEx: TypeAlias = (
set[int]
| set[str]
| dict[int, "ModelDumpIncEx"]
| dict[str, "ModelDumpIncEx"]
| None
)
"""Common include/exclude shape accepted by all supported pydantic versions."""
__all__ = (
"DEFAULT_CONFIG",
"PYDANTIC_V2",
@@ -230,16 +242,17 @@ if PYDANTIC_V2: # pragma: pydantic-v2
def model_dump(
model: BaseModel,
include: set[str] | None = None,
exclude: set[str] | None = None,
include: ModelDumpIncEx = None,
exclude: ModelDumpIncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
) -> dict[str, Any]:
return model.model_dump(
include=include,
exclude=exclude,
# Nested types cannot be inferred correctly
include=cast(Any, include),
exclude=cast(Any, exclude),
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
@@ -457,16 +470,16 @@ else: # pragma: pydantic-v1
def model_dump(
model: BaseModel,
include: set[str] | None = None,
exclude: set[str] | None = None,
include: ModelDumpIncEx = None,
exclude: ModelDumpIncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
) -> dict[str, Any]:
return model.dict(
include=include,
exclude=exclude,
include=cast(Any, include),
exclude=cast(Any, exclude),
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,