22
33import os
44import inspect
5+ import weakref
56from typing import TYPE_CHECKING , Any , Type , Union , Generic , TypeVar , Callable , Optional , cast
67from datetime import date , datetime
78from typing_extensions import (
@@ -257,32 +258,41 @@ def model_dump(
257258 mode : Literal ["json" , "python" ] | str = "python" ,
258259 include : IncEx | None = None ,
259260 exclude : IncEx | None = None ,
261+ context : Any | None = None ,
260262 by_alias : bool | None = None ,
261263 exclude_unset : bool = False ,
262264 exclude_defaults : bool = False ,
263265 exclude_none : bool = False ,
266+ exclude_computed_fields : bool = False ,
264267 round_trip : bool = False ,
265268 warnings : bool | Literal ["none" , "warn" , "error" ] = True ,
266- context : dict [str , Any ] | None = None ,
267- serialize_as_any : bool = False ,
268269 fallback : Callable [[Any ], Any ] | None = None ,
270+ serialize_as_any : bool = False ,
269271 ) -> dict [str , Any ]:
270272 """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
271273
272274 Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
273275
274276 Args:
275277 mode: The mode in which `to_python` should run.
276- If mode is 'json', the dictionary will only contain JSON serializable types.
277- If mode is 'python', the dictionary may contain any Python objects.
278- include: A list of fields to include in the output.
279- exclude: A list of fields to exclude from the output.
278+ If mode is 'json', the output will only contain JSON serializable types.
279+ If mode is 'python', the output may contain non-JSON-serializable Python objects.
280+ include: A set of fields to include in the output.
281+ exclude: A set of fields to exclude from the output.
282+ context: Additional context to pass to the serializer.
280283 by_alias: Whether to use the field's alias in the dictionary key if defined.
281- exclude_unset: Whether to exclude fields that are unset or None from the output.
282- exclude_defaults: Whether to exclude fields that are set to their default value from the output.
283- exclude_none: Whether to exclude fields that have a value of `None` from the output.
284- round_trip: Whether to enable serialization and deserialization round-trip support.
285- warnings: Whether to log warnings when invalid fields are encountered.
284+ exclude_unset: Whether to exclude fields that have not been explicitly set.
285+ exclude_defaults: Whether to exclude fields that are set to their default value.
286+ exclude_none: Whether to exclude fields that have a value of `None`.
287+ exclude_computed_fields: Whether to exclude computed fields.
288+ While this can be useful for round-tripping, it is usually recommended to use the dedicated
289+ `round_trip` parameter instead.
290+ round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
291+ warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
292+ "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
293+ fallback: A function to call when an unknown value is encountered. If not provided,
294+ a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
295+ serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
286296
287297 Returns:
288298 A dictionary representation of the model.
@@ -299,6 +309,8 @@ def model_dump(
299309 raise ValueError ("serialize_as_any is only supported in Pydantic v2" )
300310 if fallback is not None :
301311 raise ValueError ("fallback is only supported in Pydantic v2" )
312+ if exclude_computed_fields != False :
313+ raise ValueError ("exclude_computed_fields is only supported in Pydantic v2" )
302314 dumped = super ().dict ( # pyright: ignore[reportDeprecated]
303315 include = include ,
304316 exclude = exclude ,
@@ -315,15 +327,17 @@ def model_dump_json(
315327 self ,
316328 * ,
317329 indent : int | None = None ,
330+ ensure_ascii : bool = False ,
318331 include : IncEx | None = None ,
319332 exclude : IncEx | None = None ,
333+ context : Any | None = None ,
320334 by_alias : bool | None = None ,
321335 exclude_unset : bool = False ,
322336 exclude_defaults : bool = False ,
323337 exclude_none : bool = False ,
338+ exclude_computed_fields : bool = False ,
324339 round_trip : bool = False ,
325340 warnings : bool | Literal ["none" , "warn" , "error" ] = True ,
326- context : dict [str , Any ] | None = None ,
327341 fallback : Callable [[Any ], Any ] | None = None ,
328342 serialize_as_any : bool = False ,
329343 ) -> str :
@@ -355,6 +369,10 @@ def model_dump_json(
355369 raise ValueError ("serialize_as_any is only supported in Pydantic v2" )
356370 if fallback is not None :
357371 raise ValueError ("fallback is only supported in Pydantic v2" )
372+ if ensure_ascii != False :
373+ raise ValueError ("ensure_ascii is only supported in Pydantic v2" )
374+ if exclude_computed_fields != False :
375+ raise ValueError ("exclude_computed_fields is only supported in Pydantic v2" )
358376 return super ().json ( # type: ignore[reportDeprecated]
359377 indent = indent ,
360378 include = include ,
@@ -574,6 +592,9 @@ class CachedDiscriminatorType(Protocol):
574592 __discriminator__ : DiscriminatorDetails
575593
576594
595+ DISCRIMINATOR_CACHE : weakref .WeakKeyDictionary [type , DiscriminatorDetails ] = weakref .WeakKeyDictionary ()
596+
597+
577598class DiscriminatorDetails :
578599 field_name : str
579600 """The name of the discriminator field in the variant class, e.g.
@@ -616,8 +637,9 @@ def __init__(
616637
617638
618639def _build_discriminated_union_meta (* , union : type , meta_annotations : tuple [Any , ...]) -> DiscriminatorDetails | None :
619- if isinstance (union , CachedDiscriminatorType ):
620- return union .__discriminator__
640+ cached = DISCRIMINATOR_CACHE .get (union )
641+ if cached is not None :
642+ return cached
621643
622644 discriminator_field_name : str | None = None
623645
@@ -670,7 +692,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
670692 discriminator_field = discriminator_field_name ,
671693 discriminator_alias = discriminator_alias ,
672694 )
673- cast ( CachedDiscriminatorType , union ). __discriminator__ = details
695+ DISCRIMINATOR_CACHE . setdefault ( union , details )
674696 return details
675697
676698
0 commit comments