We use Pydantic to set the "Domain Models" and use them across the application layer.
import datetime
from decimal import Decimal
from pydantic import BaseModel
class Person(BaseModel):
name: str
birth_date: datetime.date
height: Decimal
# other 100 fields, most of them Decimal
Now we need to export one of those models to a CSV, first implementation is easy:
import csv
from typing import Iterable
def store(persons: Iterable[Person]):
fieldnames = list(Person.schema()["properties"].keys())
with open("/tmp/test.csv", "w") as fp:
writer = csv.DictWriter(fp, fieldnames=fieldnames)
writer.writeheader()
for person in persons:
writer.writerow(person.dict())
But there is more, because we want all the decimals to be limited to two decimal places only, how can we achieve that?
Note: would not put serialization logic in the domain model, but I'm open to create a new model just for the serialization.