Skip to content

Commit 9152889

Browse files
Jacksunweicopybara-github
authored andcommitted
chore: Adds indent to YAML sequence by default for better visual readability
Both are valid YAML, just with indent, it's more visually friend to see the data structure hierarchy. Before ``` items: - item1 - item2 - item3 ``` After ``` items: - item1 - item2 - item3 ``` PiperOrigin-RevId: 806117290
1 parent f73ae6e commit 9152889

2 files changed

Lines changed: 55 additions & 2 deletions

File tree

src/google/adk/utils/yaml_utils.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,16 @@ def dump_pydantic_to_yaml(
4343
file_path = Path(file_path)
4444
file_path.parent.mkdir(parents=True, exist_ok=True)
4545

46-
# Create a custom dumper class
4746
class _MultilineDumper(yaml.SafeDumper):
48-
pass
47+
48+
def increase_indent(self, flow=False, indentless=False):
49+
"""Override to force consistent indentation for sequences in mappings.
50+
51+
By default, PyYAML uses indentless=True for sequences that are values
52+
in mappings, creating flush-left alignment. This override forces proper
53+
indentation for all sequences regardless of context.
54+
"""
55+
return super(_MultilineDumper, self).increase_indent(flow, False)
4956

5057
def multiline_str_representer(dumper, data):
5158
if '\n' in data:

tests/unittests/utils/test_yaml_utils.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ class SimpleModel(BaseModel):
3030
active: bool
3131
finish_reason: Optional[types.FinishReason] = None
3232
multiline_text: Optional[str] = None
33+
items: Optional[list[str]] = None
3334

3435

3536
def test_yaml_file_generation(tmp_path: Path):
@@ -77,3 +78,48 @@ def test_multiline_string_pipe_style(tmp_path: Path):
7778
and should be formatted with pipe style
7879
name: Test
7980
"""
81+
82+
83+
def test_list_indentation(tmp_path: Path):
84+
"""Test that lists in mappings are properly indented."""
85+
model = SimpleModel(
86+
name="Test",
87+
age=25,
88+
active=True,
89+
items=["item1", "item2", "item3"],
90+
)
91+
yaml_file = tmp_path / "test.yaml"
92+
93+
dump_pydantic_to_yaml(model, yaml_file)
94+
95+
expected = """\
96+
active: true
97+
age: 25
98+
items:
99+
- item1
100+
- item2
101+
- item3
102+
name: Test
103+
"""
104+
assert yaml_file.read_text(encoding="utf-8") == expected
105+
106+
107+
def test_empty_list_formatting(tmp_path: Path):
108+
"""Test that empty lists are formatted properly."""
109+
model = SimpleModel(
110+
name="Test",
111+
age=25,
112+
active=True,
113+
items=[],
114+
)
115+
yaml_file = tmp_path / "test.yaml"
116+
117+
dump_pydantic_to_yaml(model, yaml_file)
118+
119+
expected = """\
120+
active: true
121+
age: 25
122+
items: []
123+
name: Test
124+
"""
125+
assert yaml_file.read_text(encoding="utf-8") == expected

0 commit comments

Comments
 (0)