import io from typing import Iterator, Self, Type import pydantic class _Account(pydantic.BaseModel): name: str login: str password: str @classmethod def from_tuple(cls: Type[Self], tuple_: tuple[str, str, str]) -> Self: return cls(name=tuple_[0], login=tuple_[1], password=tuple_[2]) def as_tuple(self: Self) -> tuple[str, str, str]: return (self.name, self.login, self.password) class _Accounts(pydantic.BaseModel): accounts: list[_Account] = pydantic.Field(default_factory=list) def _accounts_list_to_json(accounts: Iterator[tuple[str, str, str]]) -> str: accounts = _Accounts(accounts=[_Account.from_tuple(i) for i in accounts]) return accounts.json() def json_to_accounts(json_: str) -> list[tuple[str, str, str]]: accounts = _Accounts.parse_raw(json_) return [i.as_tuple() for i in accounts.accounts] def accounts_to_json(accounts: Iterator[tuple[str, str, str]]) -> io.StringIO: file = io.StringIO(_accounts_list_to_json(accounts)) file.name = "passwords.json" return file