Created
May 28, 2024 13:43
-
-
Save saracen24/43965b7ae07ac584a3a7047d48c29522 to your computer and use it in GitHub Desktop.
Convert a dict of any depth to a class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Any, Dict, FrozenSet, List, Set, Tuple, Union | |
| class DictToClass: | |
| """Convert a dict of any depth to a class.""" | |
| def __init__(self, data: Dict) -> None: | |
| for name, value in data.items(): | |
| setattr(self, name, self.__expand(value)) | |
| def __expand(self, value: Any) -> Union["DictToClass", Any]: | |
| if isinstance(value, (Tuple, List, Set, FrozenSet)): | |
| return type(value)([self.__expand(v) for v in value]) | |
| else: | |
| return DictToClass(value) if isinstance(value, Dict) else value |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Output