From 3ffd6aeca62ac65275d6ad089bb837a9eba4cfb2 Mon Sep 17 00:00:00 2001 From: Vincent Gao Date: Mon, 22 Jun 2026 11:25:47 +0200 Subject: [PATCH] Preserve table display names on self assignment --- CHANGELOG.md | 1 + tests/test_toml_document.py | 14 ++++++++++++++ tomlkit/container.py | 2 +- 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index faad379..4d2be26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ - Fix a `KeyAlreadyPresent` error when parsing or accessing an out-of-order table whose array-of-tables elements are split across the table's parts. ([#505](https://github.com/python-poetry/tomlkit/issues/505)) - Out-of-order value-vs-table and dotted-key-vs-table redefinitions are now rejected at parse time instead of being silently accepted or raising only on access. The parser also detects when a non-dotted key is a prefix of an existing dotted key, matching the stdlib `tomllib` behaviour. ([#523](https://github.com/python-poetry/tomlkit/issues/523)) - Reject tables inserted into inline tables instead of serializing invalid TOML. ([#531](https://github.com/python-poetry/tomlkit/issues/531)) +- Fix a table's display name (its exact header spelling, including whitespace and quoting) being normalised when the table is assigned onto itself, e.g. `doc[k] = doc[k]` rewriting `[keys .'a'.'c']` to `[keys.a.'c']`. ([#291](https://github.com/python-poetry/tomlkit/issues/291)) ## [0.15.0] - 2026-05-10 diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index a1eea7a..36ac0de 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -1024,6 +1024,20 @@ def test_replace_super_table_preserves_whitespace() -> None: assert doc.as_string() == content +def test_replace_table_with_itself_preserves_display_name() -> None: + content = """\ +[keys.a] +[keys .'a'.'c'] + 'd' = 'e' +""" + doc = parse(content) + + for mode in doc["keys"]: + doc["keys"][mode] = doc["keys"][mode] + + assert doc.as_string() == content + + def test_replace_with_table_of_nested() -> None: example = """\ [a] diff --git a/tomlkit/container.py b/tomlkit/container.py index 0494019..310a502 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -928,7 +928,7 @@ def _replace_at( value.trivia.trail = v.trivia.trail self._body[idx] = (new_key, value) - if hasattr(value, "invalidate_display_name"): + if value is not v and hasattr(value, "invalidate_display_name"): value.invalidate_display_name() if isinstance(value, Table):