Skip to content

Commit 86a8351

Browse files
authored
Merge pull request #52 from ProtixIT/format-toml-context
Support TOML formatting with a non-empty context
2 parents 285f81b + eebee34 commit 86a8351

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

src/dataclass_binder/_impl.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -436,19 +436,22 @@ def _bind_to_class(self, toml_dict: Mapping[str, Any], instance: T | None, conte
436436
else:
437437
return replace(instance, **parsed) # type: ignore[type-var]
438438

439-
def format_toml(self) -> Iterator[str]:
439+
def format_toml(self, context: str = "") -> Iterator[str]:
440440
"""
441441
Yield lines of TOML text for populating the dataclass or object that we are binding to.
442442
443443
If we are binding to an object, non-default values from that object will be output.
444444
445445
If we are binding to a class, example values for mandatory fields will be derived from the field types;
446446
these example values can be syntactically incorrect placeholders.
447+
448+
The `context` parameter contains a dot-separated key path for the bound object/class:
449+
this will be prefixed to all yielded TOML table names.
447450
"""
448451

449-
return self._format_toml_root(template=False)
452+
return self._format_toml_root(context=context, template=False)
450453

451-
def format_toml_template(self) -> Iterator[str]:
454+
def format_toml_template(self, context: str = "") -> Iterator[str]:
452455
"""
453456
Yield lines of TOML text as a template for populating the dataclass or object that we are binding to.
454457
@@ -457,12 +460,15 @@ def format_toml_template(self) -> Iterator[str]:
457460
458461
If we are binding to an object, values from that object will be used to populate the template.
459462
If we are binding to a class, example values will be derived from the field types.
463+
464+
The `context` parameter contains a dot-separated key path for the bound object/class:
465+
this will be prefixed to all yielded TOML table names.
460466
"""
461467

462-
return self._format_toml_root(template=True)
468+
return self._format_toml_root(context=context, template=True)
463469

464-
def _format_toml_root(self, *, template: bool) -> Iterator[str]:
465-
table = Table(self, "", self._instance, None)
470+
def _format_toml_root(self, *, context: str, template: bool) -> Iterator[str]:
471+
table = Table(self, context, self._instance, None)
466472
lines = table.format_table(set(), template=template)
467473
for line in lines:
468474
if line:

tests/test_formatting.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,12 @@ class Inner:
231231
behind_the_curtain: str = field(init=False, default="wizard")
232232

233233

234+
@dataclass(kw_only=True)
235+
class Outer:
236+
top_level: int
237+
nested: Inner
238+
239+
234240
@pytest.mark.parametrize("optional", (True, False))
235241
@pytest.mark.parametrize("string", (True, False))
236242
def test_format_value_nested_dataclass(*, optional: bool, string: bool) -> None:
@@ -239,6 +245,25 @@ def test_format_value_nested_dataclass(*, optional: bool, string: bool) -> None:
239245
assert round_trip_value(value, dc) == value
240246

241247

248+
@pytest.mark.parametrize(
249+
("context", "expected_headers"),
250+
[
251+
("", ["[nested]"]),
252+
("one", ["[one]", "[one.nested]"]),
253+
("one.two", ["[one.two]", "[one.two.nested]"]),
254+
],
255+
)
256+
def test_format_value_context(context: str, expected_headers: list[str]) -> None:
257+
obj = Outer(top_level=123, nested=Inner(key_containing_underscores=True, maybesuffix=timedelta(days=2)))
258+
259+
lines = list(Binder(obj).format_toml_template(context=context))
260+
toml = "\n".join(lines)
261+
print(toml) # noqa: T201
262+
263+
actual_headers = [line for line in lines if line.startswith("[")]
264+
assert actual_headers == expected_headers
265+
266+
242267
def test_format_value_unsupported_type() -> None:
243268
with pytest.raises(TypeError, match=r"^NoneType$"):
244269
format_toml_pair("unsupported", None)

0 commit comments

Comments
 (0)