Skip to content

Instantly share code, notes, and snippets.

@transistor1
Created May 19, 2024 02:02
Show Gist options
  • Save transistor1/8fa1379c509ae6f82a7ebcb4f62e4878 to your computer and use it in GitHub Desktop.
Save transistor1/8fa1379c509ae6f82a7ebcb4f62e4878 to your computer and use it in GitHub Desktop.
Wraps a dict object in a namespace object recursively
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