|
| 1 | +import json |
| 2 | +from typing import Self |
| 3 | + |
| 4 | + |
| 5 | +class SerializableMixin: |
| 6 | + def serialize(self) -> dict: |
| 7 | + if hasattr(self, "__slots__"): |
| 8 | + return {name: getattr(self, name) for name in self.__slots__} |
| 9 | + else: |
| 10 | + return vars(self) |
| 11 | + |
| 12 | + |
| 13 | +class JSONSerializableMixin: |
| 14 | + @classmethod |
| 15 | + def from_json(cls, json_string: str) -> Self: |
| 16 | + return cls(**json.loads(json_string)) |
| 17 | + |
| 18 | + def as_json(self) -> str: |
| 19 | + return json.dumps(vars(self)) |
| 20 | + |
| 21 | + |
| 22 | +class TypedKeyMixin: |
| 23 | + def __init__(self, key_type, *args, **kwargs): |
| 24 | + super().__init__(*args, **kwargs) |
| 25 | + self.__type = key_type |
| 26 | + |
| 27 | + def __setitem__(self, key, value): |
| 28 | + if not isinstance(key, self.__type): |
| 29 | + raise TypeError(f"key must be {self.__type} but was {type(key)}") |
| 30 | + super().__setitem__(key, value) |
| 31 | + |
| 32 | + |
| 33 | +class TypedValueMixin: |
| 34 | + def __init__(self, value_type, *args, **kwargs): |
| 35 | + super().__init__(*args, **kwargs) |
| 36 | + self.__type = value_type |
| 37 | + |
| 38 | + def __setitem__(self, key, value): |
| 39 | + if not isinstance(value, self.__type): |
| 40 | + if not isinstance(value, self.__type): |
| 41 | + raise TypeError( |
| 42 | + f"value must be {self.__type} but was {type(value)}" |
| 43 | + ) |
| 44 | + super().__setitem__(key, value) |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + from collections import UserDict |
| 49 | + from dataclasses import dataclass |
| 50 | + from pathlib import Path |
| 51 | + from types import SimpleNamespace |
| 52 | + |
| 53 | + @dataclass |
| 54 | + class User(JSONSerializableMixin): |
| 55 | + user_id: int |
| 56 | + email: str |
| 57 | + |
| 58 | + class AppSettings(JSONSerializableMixin, SimpleNamespace): |
| 59 | + def save(self, filepath: str | Path) -> None: |
| 60 | + Path(filepath).write_text(self.as_json(), encoding="utf-8") |
| 61 | + |
| 62 | + class Inventory(TypedKeyMixin, TypedValueMixin, UserDict): |
| 63 | + pass |
| 64 | + |
| 65 | + user = User( 555, "[email protected]") |
| 66 | + print(user.as_json()) |
| 67 | + |
| 68 | + settings = AppSettings() |
| 69 | + settings.host = "localhost" |
| 70 | + settings.port = 8080 |
| 71 | + settings.debug_mode = True |
| 72 | + settings.log_file = None |
| 73 | + settings.urls = ( |
| 74 | + "https://192.168.1.200:8000", |
| 75 | + "https://192.168.1.201:8000", |
| 76 | + ) |
| 77 | + settings.save("settings.json") |
| 78 | + |
| 79 | + fruits = Inventory(str, int) |
| 80 | + fruits["apples"] = 42 |
| 81 | + |
| 82 | + try: |
| 83 | + fruits["🍌".encode("utf-8")] = 15 |
| 84 | + except TypeError as ex: |
| 85 | + print(ex) |
| 86 | + |
| 87 | + try: |
| 88 | + fruits["bananas"] = 3.5 |
| 89 | + except TypeError as ex: |
| 90 | + print(ex) |
0 commit comments