Skip to content

Commit ee3a850

Browse files
committed
Support TypedDict field as Dict[str, Any]
1 parent 95117b0 commit ee3a850

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/desert/_make.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,11 +305,19 @@ def field_for_schema(
305305
field = field_for_schema(newtype_supertype, default=default)
306306

307307
# enumerations
308-
if type(typ) is enum.EnumMeta:
308+
elif type(typ) is enum.EnumMeta:
309309
import marshmallow_enum
310310

311311
field = marshmallow_enum.EnumField(typ, metadata=metadata)
312312

313+
# TypedDict
314+
# TODO(python3.10) use t.is_typeddict
315+
elif isinstance(typ, t._TypedDictMeta):
316+
field = marshmallow.fields.Dict(
317+
keys=marshmallow.fields.String,
318+
values=marshmallow.fields.Raw,
319+
)
320+
313321
# Nested dataclasses
314322
forward_reference = getattr(typ, "__forward_arg__", None)
315323

tests/test_make.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,26 @@ class A:
437437
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
438438

439439

440+
def test_typed_dict(
441+
module: DataclassModule,
442+
assert_dump_load: AssertLoadDumpProtocol,
443+
) -> None:
444+
"""Test dataclasses with basic TypedDict support"""
445+
446+
class B(t.TypedDict):
447+
x: int
448+
449+
@module.dataclass
450+
class A:
451+
x: B
452+
453+
schema = desert.schema_class(A)()
454+
dumped = {"x": {"x": 1}}
455+
loaded = A(x={"x": 1})
456+
457+
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
458+
459+
440460
@pytest.mark.xfail(
441461
strict=True,
442462
reason=(
@@ -568,7 +588,6 @@ class A:
568588
assert schema.loads(schema.dumps(loaded)) == loaded
569589
assert schema.dump(schema.load(actually_dumped)) == actually_dumped
570590

571-
572591
def test_only() -> None:
573592
"""only() extracts the only item in an iterable."""
574593
assert desert._make.only([1]) == 1

0 commit comments

Comments
 (0)