Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Our backwards-compatibility policy can be found [here](https://github.com/python

## NEXT

- Fix string enum serialization in the tomlkit converter with tomlkit 0.15.3 and later.
([#842](https://github.com/python-attrs/cattrs/issues/842))

- Fix the msgspec converter passing typed deques directly to the encoder, which cannot serialize them. Deques are now unstructured into lists, including when nested in attrs classes or dataclasses.
([#818](https://github.com/python-attrs/cattrs/issues/818) [#819](https://github.com/python-attrs/cattrs/pull/819))

Expand Down
3 changes: 3 additions & 0 deletions src/cattrs/preconf/tomlkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def configure_converter(converter: BaseConverter):
converter.register_unstructure_hook(
bytes, lambda v: (b85encode(v) if v else b"").decode("utf8")
)
converter.register_unstructure_hook(
str, lambda v: v.value if isinstance(v, Enum) else v
)

def gen_unstructure_mapping(cl: Any, unstructure_to=None):
key_handler = str
Expand Down
29 changes: 29 additions & 0 deletions tests/test_preconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,35 @@ class A:
assert converter.loads(data, A) == A(date(2023, 1, 1))


def test_tomlkit_string_enums():
"""String enums serialize by value, including literals and collections."""
from tomlkit import dumps, loads, string

@define
class Example:
member: Everything.AStringEnum
literal: Literal[Everything.AStringEnum.A]
members: list[Everything.AStringEnum]
mapping: dict[Everything.AStringEnum, Everything.AStringEnum]

member = Everything.AStringEnum.A
original = Example(member, member, [member], {member: member})
converter = tomlkit_make_converter()

loaded = loads(dumps(converter.unstructure(original)))
assert loaded == {
"member": "a",
"literal": "a",
"members": ["a"],
"mapping": {"a": "a"},
}
assert converter.structure(loaded, Example) == original

# Preserve the existing passthrough for tomlkit string items.
item = string("plain text")
assert converter.unstructure(item) is item


@given(
everythings(
allow_null_bytes_in_keys=False,
Expand Down