Serializer: filter None fields, to avoid conflicts with nix module system

This commit is contained in:
Johannes Kirschbauer
2024-08-13 19:27:59 +02:00
parent 65497d8b4c
commit dfbe03bf6b
2 changed files with 22 additions and 1 deletions

View File

@@ -68,7 +68,8 @@ def dataclass_to_dict(obj: Any, *, use_alias: bool = True) -> Any:
field.metadata.get("alias", field.name) if use_alias else field.name
): _to_dict(getattr(obj, field.name))
for field in fields(obj)
if not field.name.startswith("_") # type: ignore
if not field.name.startswith("_")
and getattr(obj, field.name) is not None # type: ignore
}
elif isinstance(obj, list | tuple):
return [_to_dict(item) for item in obj]

View File

@@ -104,3 +104,23 @@ def test_dataclass_to_dict_defaults() -> None:
"foo": {"home": {"a": "b"}, "work": ["a", "b"]},
}
assert dataclass_to_dict(real_person) == expected
def test_filters_null_fields() -> None:
@dataclass
class Foo:
home: str | None = None
work: str | None = None
# None fields are filtered out
instance = Foo()
assert instance.home is None
assert dataclass_to_dict(instance) == {}
# fields that are set are not filtered
instance = Foo(home="home")
assert instance.home == "home"
assert instance.work is None
assert dataclass_to_dict(instance) == {"home": "home"}