Skip to content

Commit

Permalink
Support context being passed to TypeAdapter's dump_json/dump_python (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
alexcouper committed May 28, 2024
1 parent 7102ff5 commit 28b36d9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pydantic/type_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -464,6 +466,7 @@ def dump_python(
round_trip=round_trip,
warnings=warnings,
serialize_as_any=serialize_as_any,
context=context,
)

@_frame_depth(1)
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -516,6 +521,7 @@ def dump_json(
round_trip=round_trip,
warnings=warnings,
serialize_as_any=serialize_as_any,
context=context,
)

@_frame_depth(1)
Expand Down
17 changes: 17 additions & 0 deletions tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 28b36d9

Please sign in to comment.