diff --git a/pwgen_fr/word_db.py b/pwgen_fr/word_db.py index 3435997..e8e7e48 100644 --- a/pwgen_fr/word_db.py +++ b/pwgen_fr/word_db.py @@ -36,6 +36,15 @@ class Nom(t.NamedTuple): """Accorde en nombre""" return getattr(self, nombre.name.lower()) + @property + def serialized(self): + return {"genre": self.genre.name, "sing": self.sing, "plur": self.plur} + + @classmethod + def unserialized(cls, **kwargs): + genre = Genre(kwargs.pop("genre")) + return cls(**kwargs, genre=genre) + class Adjectif(t.NamedTuple): masc_sing: str @@ -50,6 +59,14 @@ class Adjectif(t.NamedTuple): """Accorde en genre et en nombre""" return getattr(self, f"{genre.name.lower()}_{nombre.name.lower()}") + @property + def serialized(self): + return self._asdict() + + @classmethod + def unserialized(cls, **kwargs): + return cls(**kwargs) + class Verbe(t.NamedTuple): present_sing: str @@ -66,6 +83,14 @@ class Verbe(t.NamedTuple): """Accorde en temps et en nombre (seule la 3è pers. est utilisée)""" return getattr(self, f"{temps.name.lower()}_{nombre.name.lower()}") + @property + def serialized(self): + return self._asdict() + + @classmethod + def unserialized(cls, **kwargs): + return cls(**kwargs) + class Adverbe(t.NamedTuple): """Packed as named tuple for consistence""" @@ -79,6 +104,14 @@ class Adverbe(t.NamedTuple): """for consistence""" return self.adv + @property + def serialized(self): + return self._asdict() + + @classmethod + def unserialized(cls, **kwargs): + return cls(**kwargs) + class WordDb: """Base de donnée de mots, sérialisable""" @@ -117,7 +150,7 @@ class WordDb: def serialize(self) -> dict: """Serialize to plain dictionary (no classes)""" return { - attr: [x._asdict() for x in getattr(self, attr)] + attr: [x.serialized for x in getattr(self, attr)] for attr in self.__class__._serialize_data } @@ -131,7 +164,7 @@ class WordDb: """Reverses :serialize:""" parsed = {} for attr, attr_cls in cls._serialize_data.items(): - parsed[attr] = list(map(attr_cls, data[attr])) + parsed[attr] = list(map(attr_cls.unserialized, data[attr])) return cls(**parsed) @classmethod