From 4928ee818bd202d3ca2627b66343d36405cda1f6 Mon Sep 17 00:00:00 2001 From: haigou-web Date: Sat, 28 Nov 2026 14:35:13 +0800 Subject: [PATCH] fix: write the underlying characters of str subclasses in dumps() escape_string() called str(s), which dispatches to an overridden __str__ on a str subclass. str-based Enum members were therefore serialized as their repr-like Enum form and custom wrappers produced invalid TOML that could not be parsed back. This restores the 0.15.2 behavior lost in the single-pass escaping rewrite. String itself is unaffected: its __str__ is str.__str__, so the fast path stays as fast as before. --- CHANGELOG.md | 4 ++++ tests/test_utils.py | 55 +++++++++++++++++++++++++++++++++++++++++++++ tomlkit/_utils.py | 7 +++++- 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29373b09..4a15260d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ - Speed up parsing of comments: the comment text is scanned in one pass up to the line break or the first invalid control character, instead of one character at a time. ([#723](https://github.com/python-poetry/tomlkit/pull/723)) +### Fixed + +- `item()` and `dumps()` now write the underlying characters of a `str` subclass instead of calling its `__str__` method, so `str`-based `Enum` members and custom string wrappers round-trip again instead of being serialized as e.g. `"Color.RED"` or producing invalid TOML. This was a regression from the single-pass escaping added in 0.15.3. ([#725](https://github.com/python-poetry/tomlkit/issues/725)) + ## [0.15.3] - 2026-11-24 ### Changed diff --git a/tests/test_utils.py b/tests/test_utils.py index d80cc9b1..4352de0e 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -3,11 +3,15 @@ from datetime import time from datetime import timedelta as td from datetime import timezone as tz +from enum import Enum from typing import Union import pytest +import tomlkit + from tomlkit._utils import _utc +from tomlkit._utils import escape_string from tomlkit._utils import parse_rfc3339 @@ -62,3 +66,54 @@ def test_parse_rfc3339_date(string: str, expected: Union[dt, date, time]) -> Non ) def test_parse_rfc3339_time(string: str, expected: Union[dt, date, time]) -> None: assert parse_rfc3339(string) == expected + + +class _Color(str, Enum): + RED = "red" + + +class _Quoted(str): + def __str__(self) -> str: + return f'"{super().__str__()}"' + + +def test_escape_string_returns_plain_str() -> None: + result = escape_string("hello") + + assert result == "hello" + assert type(result) is str + + +def test_escape_string_str_subclass_stays_plain_str() -> None: + """Issue #725: a ``str`` subclass must keep its characters, not its ``__str__``.""" + result = escape_string(_Quoted("plain")) + + assert result == "plain" + assert type(result) is str + + +def test_escape_string_str_subclass_with_sequences_stays_plain_str() -> None: + """Issue #725: the escaping branch must not leak the subclass either.""" + result = escape_string(_Quoted("a\nb")) + + assert result == "a\\nb" + assert type(result) is str + + +def test_dumps_str_enum_writes_value() -> None: + """Issue #725: ``dumps`` wrote ``"Color.RED"`` instead of ``"red"``.""" + document = tomlkit.document() + document["color"] = _Color.RED + + assert tomlkit.dumps(document) == 'color = "red"\n' + + +def test_dumps_str_subclass_with_custom_str_round_trips() -> None: + """Issue #725: the emitted document could not be re-parsed.""" + document = tomlkit.document() + document["k"] = _Quoted("shown") + + dumped = tomlkit.dumps(document) + + assert dumped == 'k = "shown"\n' + assert tomlkit.parse(dumped)["k"] == "shown" diff --git a/tomlkit/_utils.py b/tomlkit/_utils.py index 1aa374f9..3f9a79a0 100644 --- a/tomlkit/_utils.py +++ b/tomlkit/_utils.py @@ -147,7 +147,12 @@ def escape_string(s: str, escape_sequences: Collection[str] = _basic_escapes) -> found_sequences = [seq for seq in escape_sequences if seq in s] if not found_sequences: # always return a plain str, also for str subclasses such as String - return str(s) + # NOTE: calling `str(s)` here would dispatch to an overridden + # `__str__` on a str subclass (e.g. `enum.StrEnum` or a custom + # wrapper) and serialize that representation instead of the + # underlying characters. `str.__str__` unboxes to a plain `str` + # without invoking the subclass implementation. + return str.__str__(s) # Replace every sequence in a single left-to-right pass. Longer sequences # come first so that '"""' is matched as a whole.