Coverage for flogin/jsonrpc/base_object.py: 100%
23 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-03 22:51 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-03 22:51 +0000
1import json
2from typing import Any, ClassVar, Generic, Self, TypeVar, cast
4T = TypeVar("T")
6__all__ = ("Base",)
9class Base(Generic[T]):
10 __slots__ = ()
11 __jsonrpc_option_names__: ClassVar[dict[str, str]] = {}
13 def to_dict(self) -> T:
14 names = self.__jsonrpc_option_names__ or {}
15 foo = {}
16 for name in self.__slots__:
17 item: Any = getattr(self, name)
18 if isinstance(item, Base):
19 item = item.to_dict()
20 elif item and isinstance(item, list) and isinstance(item[0], Base):
21 item = [child.to_dict() for child in cast("list[Base[Any]]", item)]
22 foo[names.get(name, name)] = item
24 return cast("T", foo)
26 @classmethod
27 def from_dict(cls: type[Self], data: T) -> Self:
28 raise NotImplementedError
30 def __repr__(self) -> str:
31 args = [f"{item}={getattr(self, item)!r}" for item in self.__slots__]
32 return f"<{self.__class__.__name__} {' '.join(args)}>"
35class ToMessageBase(Base[T], Generic[T]):
36 def to_message(self, id: int) -> bytes:
37 return (json.dumps(self.to_dict()) + "\r\n").encode()