Skip to content

Instantly share code, notes, and snippets.

@taikedz
Created December 5, 2023 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taikedz/1affd8ee62a26d5765d38af0f3e1c669 to your computer and use it in GitHub Desktop.
Save taikedz/1affd8ee62a26d5765d38af0f3e1c669 to your computer and use it in GitHub Desktop.
Basic attributes dictionary / namespacer

DictNamespace

A basic namespacing utility to provide "nicer" code.

It's a small snippet for a minor quality-of-life utility.

ns = DictNamesspace(a=1, b="hello")
assert ns.a == 1
assert ns.b == "hello"

import json
ns = DictNamespace(json.dumps(data))
assert ns.deep.listitem[5].name == "something"
assert ns["deep"]["listitem"][5]["name"] == "something"
class DictNamespace(dict):
__INHERENT = dir(dict)
def __setitem__(self, k, v):
if k in DictNamespace.__INHERENT:
raise KeyError(f"Cannot override reserved name '{k}'")
dict.__setitem__(self, k, v)
def __setattr__(self, k, v):
self[k] = v
def __getattr__(self, k):
return self[k]
def __delattr__(self, k):
del self[k]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment