diff --git a/CHANGELOG.md b/CHANGELOG.md index c24bf2ba..ba3486df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Fixed - Arithmetic and `replace()` results for `Integer`, `Float`, `String`, `DateTime`, `Date` and `Time` no longer share the original item's `Trivia`, so changing the result's comment or indentation no longer rewrites the item still stored in the document. +- Fix an `AttributeError` when a table is defined out of order under an indented header nested four or more levels deep, e.g. ` [a.b.c.d]` then `[a.b.c]`. ([#663](https://github.com/python-poetry/tomlkit/pull/663)) ## [0.15.2] - 2026-10-16 diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index d1ef245e..f29c9078 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -743,6 +743,25 @@ def test_valid_out_of_order_super_table_extended_by_dotted_key() -> None: assert doc.as_string() == "[a.b.c]\n[a]\nb.z = 1\n" +@pytest.mark.parametrize( + ("content", "expected"), + [ + (" [a.b.c.d]\n[a.b.c]\n", {"a": {"b": {"c": {"d": {}}}}}), + (" [[a.b.c.d]]\n[a.b.c]\n", {"a": {"b": {"c": {"d": [{}]}}}}), + (" [a.b.c.d]\n[x]\n[a.b.c]\n", {"a": {"b": {"c": {"d": {}}}}, "x": {}}), + ], +) +def test_out_of_order_table_after_indented_header( + content: str, expected: dict[str, Any] +) -> None: + # https://github.com/python-poetry/tomlkit/issues/263 covered `[a.b]` after + # an indented `[[a.b.c]]`. One level deeper, the out-of-order table lands + # under an intermediate table that carries the header's indent. + doc = parse(content) + assert doc.unwrap() == expected + assert doc.as_string() == content + + def test_set_value_on_out_of_order_table_with_empty_concrete_part() -> None: # A super table defined after its sub-table (the "defining a super-table # afterward is ok" spec example) leaves an empty concrete `[x]` part. diff --git a/tomlkit/items.py b/tomlkit/items.py index 4c28af95..67e90dbb 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1969,7 +1969,9 @@ def append(self, key: Key | str | None, _item: Any) -> Table: indent = m.group(1) - if not isinstance(_item, Whitespace): + # A table split out of order is looked up as an OutOfOrderTableProxy, + # which has no trivia; its parts keep their own indentation. + if isinstance(_item, Item) and not isinstance(_item, Whitespace): m = re.match("(?s)^([^ ]*)(.*)$", _item.trivia.indent) if not m: _item.trivia.indent = indent