import copy from typing import Optional, Any class FromDictObject: """Class for creating objects from dict recursively.""" def __init__(self, **data): """ :param data: dict of attributes. """ for key, value in data.items(): self.node_to_object(value, data, key) self.__dict__.update(data) def _asdict(self): return copy.deepcopy(self.__dict__) def get(self, key: str) -> Optional[Any]: return self.__dict__.get(key) def __repr__(self): return f"{super().__repr__()}: {self.__dict__}" @staticmethod def node_to_object(node, outer, key_or_index): """Replaces one node that corresponds to the key or index "key_or_index" in the dictionary or list "outer" with a new value, depending on the type of entity. :param node: processing node - value from dictionary or element from list. :param outer: outer node data structure - dictionary or list. :param key_or_index: key or index of node in outer structure. """ if isinstance(node, dict): outer[key_or_index] = FromDictObject(**node) elif isinstance(node, list): for index, el in enumerate(node): FromDictObject.node_to_object(el, node, index)