Skip to content

Commit 903c2e9

Browse files
authored
fix: auto-determine if a table is a super table if not specified explicitly (#246)
1 parent cb822da commit 903c2e9

File tree

3 files changed

+11
-7
lines changed

3 files changed

+11
-7
lines changed

tomlkit/api.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from collections.abc import Mapping
44
from typing import IO
55
from typing import Iterable
6+
from typing import Optional
67
from typing import Tuple
78
from typing import Union
89

@@ -174,7 +175,7 @@ def array(raw: str = None) -> Array:
174175
return value(raw)
175176

176177

177-
def table(is_super_table: bool = False) -> Table:
178+
def table(is_super_table: Optional[bool] = None) -> Table:
178179
"""Create an empty table.
179180
180181
:param is_super_table: if true, the table is a super table

tomlkit/items.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -179,10 +179,6 @@ def item(
179179
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
180180
):
181181
val[k] = item(v, _parent=val, _sort_keys=_sort_keys)
182-
only_child = val[next(iter(value))] if len(value) == 1 else None
183-
if table_constructor is Table and isinstance(only_child, (AoT, Table)):
184-
# The table becomes super table if the only child is a table or AoT.
185-
val._is_super_table = True
186182

187183
return val
188184
elif isinstance(value, (list, tuple)):
@@ -1553,7 +1549,7 @@ def __init__(
15531549
value: "container.Container",
15541550
trivia: Trivia,
15551551
is_aot_element: bool,
1556-
is_super_table: bool = False,
1552+
is_super_table: Optional[bool] = None,
15571553
name: Optional[str] = None,
15581554
display_name: Optional[str] = None,
15591555
) -> None:
@@ -1632,7 +1628,13 @@ def is_aot_element(self) -> bool:
16321628
def is_super_table(self) -> bool:
16331629
"""A super table is the intermediate parent of a nested table as in [a.b.c].
16341630
If true, it won't appear in the TOML representation."""
1635-
return self._is_super_table
1631+
if self._is_super_table is not None:
1632+
return self._is_super_table
1633+
# If the table has only one child and that child is a table, then it is a super table.
1634+
if len(self) != 1:
1635+
return False
1636+
only_child = next(iter(self.values()))
1637+
return isinstance(only_child, (Table, AoT))
16361638

16371639
def as_string(self) -> str:
16381640
return self._value.as_string()

tomlkit/parser.py

+1
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,7 @@ def _parse_table(
948948
is_aot,
949949
name=name_parts[0].key if name_parts else key.key,
950950
display_name=full_key.as_string(),
951+
is_super_table=False,
951952
)
952953

953954
if len(name_parts) > 1:

0 commit comments

Comments
 (0)