GNU/Linux xterm-256color zsh 94 views

Example use of the dc-input library: https://github.com/jdvanwijk/dc-input

Script used for this example:


from dataclasses import dataclass, field
import datetime
from pprint import pprint
from typing import Annotated, Any

from dc_input import get_input

@dataclass
class Name:
    first: str
    middle: list[str]
    last: str

    full: str = field(init=False)

    def __post_init__(self) -> None:
        middle = f" {' '.join(name for name in self.middle)} " if self.middle else " "
        self.full = f"{self.first}{middle}{self.last}"


@dataclass
class Address:
    street: str
    street_number: int
    apartment: str | None
    zip_code: Annotated[int, "XXXXX"]
    city: str = "Berlin"


@dataclass
class Instrument:
    name: str
    start_date: Annotated[datetime.date | None, "DD/MM/YYYY"]
    comment: str | None


@dataclass
class MusicStudent:
    id: int

    name: Name
    date_of_birth: Annotated[datetime.date, "DD/MM/YYYY"]
    address: Annotated[Address, "Must be a German address"]

    primary_instrument: Instrument
    secondary_instruments: Annotated[
        list[Instrument], "Other instruments the student may have experience with"
    ]

    comments: str | None


def parse_date_dmy(s: str) -> datetime.date:
    s = s.strip().replace(".", "/").replace("-", "/")
    try:
        day, month, year = map(int, s.split("/"))
    except Exception:
        raise ValueError("wrong format, must be DD/MM/YYYY")
    else:
        return datetime.date(year, month, day)


if __name__ == "__main__":
    result = get_input(MusicStudent, parsers={datetime.date: parse_date_dmy})
    pprint(result)

More recordings by janebelvanwijk