From a2889bd13c939d7edbc489a86e6450db571c2cd4 Mon Sep 17 00:00:00 2001 From: Daniele Barile <61387309+Ho3pLi@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:42:45 +0100 Subject: [PATCH] Fix string enum serialization with tomlkit 0.15.3 (#842) --- HISTORY.md | 3 +++ src/cattrs/preconf/tomlkit.py | 3 +++ tests/test_preconf.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/HISTORY.md b/HISTORY.md index 942616e3..10ca0148 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -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)) diff --git a/src/cattrs/preconf/tomlkit.py b/src/cattrs/preconf/tomlkit.py index a5735117..e231b229 100644 --- a/src/cattrs/preconf/tomlkit.py +++ b/src/cattrs/preconf/tomlkit.py @@ -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 diff --git a/tests/test_preconf.py b/tests/test_preconf.py index 18258502..057d4dd3 100644 --- a/tests/test_preconf.py +++ b/tests/test_preconf.py @@ -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,