Skip to content

Commit

Permalink
Fix serialization for lists of dicts in YAML
Browse files Browse the repository at this point in the history
  • Loading branch information
jacebrowning committed Jan 15, 2022
1 parent 359e26c commit acd0412
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 43 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

- Added support for Python 3.10's builtin optional types (e.g. `int | None`).
- Fixed handling of commented blocks in YAML files.
- Fixed serialization for `list` of `dict` in YAML.

# 1.0 (2021-10-04)

Expand Down
11 changes: 8 additions & 3 deletions datafiles/formats.py
Expand Up @@ -5,7 +5,7 @@
from contextlib import suppress
from io import StringIO
from pathlib import Path
from typing import IO, Dict, List
from typing import IO, Dict, List, Union

import log

Expand Down Expand Up @@ -105,7 +105,10 @@ def serialize(cls, data):

stream = StringIO()
yaml.dump(data, stream)
text = stream.getvalue().strip() + '\n'
text = stream.getvalue()

if text.startswith(' '):
return text[2:].replace('\n ', '\n')

if text == "{}\n":
return ""
Expand All @@ -127,7 +130,9 @@ def deserialize(path: Path, extension: str, *, formatter=None) -> Dict:
return data


def serialize(data: Dict, extension: str = '.yml', *, formatter=None) -> str:
def serialize(
data: Union[Dict, List], extension: str = '.yml', *, formatter=None
) -> str:
if formatter is None:
formatter = _get_formatter(extension)
return formatter.serialize(data)
Expand Down
10 changes: 10 additions & 0 deletions datafiles/tests/test_formats.py
Expand Up @@ -30,6 +30,16 @@ def it_indents_blocks_by_default(expect, data):
"""
)

def it_handles_lists_of_dicts(expect):
data = [{"one": 1, "two": 2}]
text = formats.serialize(data, '.yaml')
expect(text) == dedent(
"""
- one: 1
two: 2
"""
)


def describe_deserialize():
@pytest.fixture
Expand Down
70 changes: 32 additions & 38 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pyproject.toml
@@ -1,7 +1,7 @@
[tool.poetry]

name = "datafiles"
version = "1.1b2"
version = "1.1b3"
description = "File-based ORM for dataclasses."

license = "MIT"
Expand Down Expand Up @@ -44,7 +44,7 @@ classifiers = [
python = "^3.7"

# Formats
"ruamel.yaml" = "^0.17.17"
"ruamel.yaml" = "^0.17.20"
tomlkit = "^0.7.2"

# ORM
Expand Down

0 comments on commit acd0412

Please sign in to comment.