Created
May 19, 2024 02:02
-
-
Save transistor1/8fa1379c509ae6f82a7ebcb4f62e4878 to your computer and use it in GitHub Desktop.
Wraps a dict object in a namespace object recursively
This file contains 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
class nswrap: | |
"""Wraps a dict object in a namespace object recursively. | |
Like SimpleNamespace, except recursive. Makes discovery of | |
dictionaries easier in JupyterLab. | |
""" | |
def __init__(self, d): | |
"""_summary_ | |
Args: | |
d (dict): A dictionary | |
""" | |
for k in d.keys(): | |
if type(d[k]) is dict: | |
d[k] = nswrap(d[k]) | |
self.__attrs__ = d | |
self.__dict__ = {**self.__attrs__, '__attrs__': d} | |
def __str__(self): | |
from pprint import pformat | |
return f'nswrap({pformat(self.__attrs__)})' | |
def __repr__(self): | |
return self.__str__() | |
def __getattribute__(self, name): | |
attr = object.__getattribute__(self, name) | |
if name[0] == '_': | |
return attr | |
if type(attr) == dict: | |
return nswrap(attr) | |
elif type(attr) == list: | |
attr = [nswrap(i) if type(i) is dict else i for i in attr] | |
return attr | |
else: | |
return attr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment