Skip to content

Commit 98d092e

Browse files
committed
Add module to write party to TOML document
1 parent 846ad57 commit 98d092e

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
## 0.6.0 (unreleased)
55

6+
- Added module to write a party to a TOML document.
7+
68

79
## 0.5.0 (2024-06-30)
810

pyproject.toml

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ description = "Python library for the OrgaTalk LAN Party Database"
55
authors = [
66
{ name = "Jochen Kupperschmidt", email = "[email protected]" }
77
]
8-
dependencies = []
8+
dependencies = [
9+
"tomlkit>=0.12.5",
10+
]
911
readme = "README.md"
1012
requires-python = ">= 3.11"
1113
license = { text = "MIT" }

src/lanpartydb/writing.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
lanpartydb.writing
3+
~~~~~~~~~~~~~~~~~~
4+
5+
Data writing
6+
7+
:Copyright: 2024 Jochen Kupperschmidt
8+
:License: MIT
9+
"""
10+
11+
import dataclasses
12+
from typing import Any
13+
14+
from lanpartydb.models import Party
15+
import tomlkit
16+
17+
18+
# party
19+
20+
21+
def serialize_party(party: Party) -> str:
22+
"""Serialize party to TOML document."""
23+
party_dict = _party_to_sparse_dict(party)
24+
return _write_toml(party_dict)
25+
26+
27+
def _party_to_sparse_dict(party: Party) -> dict[str, Any]:
28+
data = dataclasses.asdict(party)
29+
_remove_default_values(data)
30+
return data
31+
32+
33+
# util
34+
35+
36+
def _write_toml(d: dict[str, Any]) -> str:
37+
return tomlkit.dumps(d)
38+
39+
40+
def _remove_default_values(d: dict[str, Any]) -> dict[str, Any]:
41+
"""Remove `None` and `False`, values from first level of dictionary."""
42+
for k, v in list(d.items()):
43+
if (v is None) or (v is False):
44+
del d[k]
45+
elif isinstance(v, dict):
46+
_remove_default_values(v)
47+
48+
return d

0 commit comments

Comments
 (0)