home · contact · privacy
Slightly reduce the do_POST_todo code.
[plomtask] / plomtask / misc.py
1 """What doesn't fit elsewhere so far."""
2 from typing import Any
3
4
5 class DictableNode:
6     """Template for display chain nodes providing .as_dict_and_refs."""
7     # pylint: disable=too-few-public-methods
8     _to_dict: list[str] = []
9
10     def __init__(self, *args: Any) -> None:
11         for i, arg in enumerate(args):
12             setattr(self, self._to_dict[i], arg)
13
14     @property
15     def as_dict_and_refs(self) -> tuple[dict[str, object], list[Any]]:
16         """Return self as json.dumps-ready dict, list of referenced objects."""
17         d = {}
18         refs = []
19         for name in self._to_dict:
20             attr = getattr(self, name)
21             if hasattr(attr, 'id_'):
22                 d[name] = attr.id_
23                 continue
24             if isinstance(attr, list):
25                 d[name] = []
26                 for item in attr:
27                     item_d, item_refs = item.as_dict_and_refs
28                     d[name] += [item_d]
29                     for item_ref in [r for r in item_refs if r not in refs]:
30                         refs += [item_ref]
31                 continue
32             d[name] = attr
33         return d, refs