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 (
@@ -256,32 +257,41 @@ def model_dump(
256257 mode : Literal ["json" , "python" ] | str = "python" ,
257258 include : IncEx | None = None ,
258259 exclude : IncEx | None = None ,
260+ context : Any | None = None ,
259261 by_alias : bool | None = None ,
260262 exclude_unset : bool = False ,
261263 exclude_defaults : bool = False ,
262264 exclude_none : bool = False ,
265+ exclude_computed_fields : bool = False ,
263266 round_trip : bool = False ,
264267 warnings : bool | Literal ["none" , "warn" , "error" ] = True ,
265- context : dict [str , Any ] | None = None ,
266- serialize_as_any : bool = False ,
267268 fallback : Callable [[Any ], Any ] | None = None ,
269+ serialize_as_any : bool = False ,
268270 ) -> dict [str , Any ]:
269271 """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
270272
271273 Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
272274
273275 Args:
274276 mode: The mode in which `to_python` should run.
275- If mode is 'json', the dictionary will only contain JSON serializable types.
276- If mode is 'python', the dictionary may contain any Python objects.
277- include: A list of fields to include in the output.
278- exclude: A list of fields to exclude from the output.
277+ If mode is 'json', the output will only contain JSON serializable types.
278+ If mode is 'python', the output may contain non-JSON-serializable Python objects.
279+ include: A set of fields to include in the output.
280+ exclude: A set of fields to exclude from the output.
281+ context: Additional context to pass to the serializer.
279282 by_alias: Whether to use the field's alias in the dictionary key if defined.
280- exclude_unset: Whether to exclude fields that are unset or None from the output.
281- exclude_defaults: Whether to exclude fields that are set to their default value from the output.
282- exclude_none: Whether to exclude fields that have a value of `None` from the output.
283- round_trip: Whether to enable serialization and deserialization round-trip support.
284- warnings: Whether to log warnings when invalid fields are encountered.
283+ exclude_unset: Whether to exclude fields that have not been explicitly set.
284+ exclude_defaults: Whether to exclude fields that are set to their default value.
285+ exclude_none: Whether to exclude fields that have a value of `None`.
286+ exclude_computed_fields: Whether to exclude computed fields.
287+ While this can be useful for round-tripping, it is usually recommended to use the dedicated
288+ `round_trip` parameter instead.
289+ round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
290+ warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
291+ "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
292+ fallback: A function to call when an unknown value is encountered. If not provided,
293+ a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
294+ serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
285295
286296 Returns:
287297 A dictionary representation of the model.
@@ -298,6 +308,8 @@ def model_dump(
298308 raise ValueError ("serialize_as_any is only supported in Pydantic v2" )
299309 if fallback is not None :
300310 raise ValueError ("fallback is only supported in Pydantic v2" )
311+ if exclude_computed_fields != False :
312+ raise ValueError ("exclude_computed_fields is only supported in Pydantic v2" )
301313 dumped = super ().dict ( # pyright: ignore[reportDeprecated]
302314 include = include ,
303315 exclude = exclude ,
@@ -314,15 +326,17 @@ def model_dump_json(
314326 self ,
315327 * ,
316328 indent : int | None = None ,
329+ ensure_ascii : bool = False ,
317330 include : IncEx | None = None ,
318331 exclude : IncEx | None = None ,
332+ context : Any | None = None ,
319333 by_alias : bool | None = None ,
320334 exclude_unset : bool = False ,
321335 exclude_defaults : bool = False ,
322336 exclude_none : bool = False ,
337+ exclude_computed_fields : bool = False ,
323338 round_trip : bool = False ,
324339 warnings : bool | Literal ["none" , "warn" , "error" ] = True ,
325- context : dict [str , Any ] | None = None ,
326340 fallback : Callable [[Any ], Any ] | None = None ,
327341 serialize_as_any : bool = False ,
328342 ) -> str :
@@ -354,6 +368,10 @@ def model_dump_json(
354368 raise ValueError ("serialize_as_any is only supported in Pydantic v2" )
355369 if fallback is not None :
356370 raise ValueError ("fallback is only supported in Pydantic v2" )
371+ if ensure_ascii != False :
372+ raise ValueError ("ensure_ascii is only supported in Pydantic v2" )
373+ if exclude_computed_fields != False :
374+ raise ValueError ("exclude_computed_fields is only supported in Pydantic v2" )
357375 return super ().json ( # type: ignore[reportDeprecated]
358376 indent = indent ,
359377 include = include ,
@@ -573,6 +591,9 @@ class CachedDiscriminatorType(Protocol):
573591 __discriminator__ : DiscriminatorDetails
574592
575593
594+ DISCRIMINATOR_CACHE : weakref .WeakKeyDictionary [type , DiscriminatorDetails ] = weakref .WeakKeyDictionary ()
595+
596+
576597class DiscriminatorDetails :
577598 field_name : str
578599 """The name of the discriminator field in the variant class, e.g.
@@ -615,8 +636,9 @@ def __init__(
615636
616637
617638def _build_discriminated_union_meta (* , union : type , meta_annotations : tuple [Any , ...]) -> DiscriminatorDetails | None :
618- if isinstance (union , CachedDiscriminatorType ):
619- return union .__discriminator__
639+ cached = DISCRIMINATOR_CACHE .get (union )
640+ if cached is not None :
641+ return cached
620642
621643 discriminator_field_name : str | None = None
622644
@@ -669,7 +691,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any,
669691 discriminator_field = discriminator_field_name ,
670692 discriminator_alias = discriminator_alias ,
671693 )
672- cast ( CachedDiscriminatorType , union ). __discriminator__ = details
694+ DISCRIMINATOR_CACHE . setdefault ( union , details )
673695 return details
674696
675697
0 commit comments