diff --git a/pydantic/type_adapter.py b/pydantic/type_adapter.py index fc5b6824a3..fc5a032e22 100644 --- a/pydantic/type_adapter.py +++ b/pydantic/type_adapter.py @@ -432,6 +432,7 @@ def dump_python( round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False, + context: dict[str, Any] | None = None, ) -> Any: """Dump an instance of the adapted type to a Python object. @@ -448,6 +449,7 @@ def dump_python( warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: Additional context to pass to the serializer. Returns: The serialized object. @@ -464,6 +466,7 @@ def dump_python( round_trip=round_trip, warnings=warnings, serialize_as_any=serialize_as_any, + context=context, ) @_frame_depth(1) @@ -482,6 +485,7 @@ def dump_json( round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, serialize_as_any: bool = False, + context: dict[str, Any] | None = None, ) -> bytes: """Usage docs: https://docs.pydantic.dev/2.8/concepts/json/#json-serialization @@ -500,6 +504,7 @@ def dump_json( warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: Additional context to pass to the serializer. Returns: The JSON representation of the given instance as bytes. @@ -516,6 +521,7 @@ def dump_json( round_trip=round_trip, warnings=warnings, serialize_as_any=serialize_as_any, + context=context, ) @_frame_depth(1) diff --git a/tests/test_serialize.py b/tests/test_serialize.py index 52b3fdea2b..c28debcbb6 100644 --- a/tests/test_serialize.py +++ b/tests/test_serialize.py @@ -900,6 +900,23 @@ def ser_model(self) -> Dict[str, Any]: assert ta.dump_json(Model({'x': 1, 'y': 2.5})) == b'{"x":2,"y":7.5}' +def test_type_adapter_dump_with_context(): + class Model(TypedDict): + x: int + y: float + + @model_serializer(mode='wrap') + def _serialize(self, handler, info: Optional[SerializationInfo] = None): + data = handler(self) + if info.context and info.context.get('mode') == 'x-only': + data.pop('y') + return data + + ta = TypeAdapter(Model) + + assert ta.dump_json(Model({'x': 1, 'y': 2.5}), context={'mode': 'x-only'}) == b'{"x":1}' + + @pytest.mark.parametrize('as_annotation', [True, False]) @pytest.mark.parametrize('mode', ['plain', 'wrap']) def test_forward_ref_for_serializers(as_annotation, mode):