Skip to content

Instantly share code, notes, and snippets.

@sirkonst
Last active May 26, 2016 12:22
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 sirkonst/435f16adad834370044e to your computer and use it in GitHub Desktop.
Save sirkonst/435f16adad834370044e to your computer and use it in GitHub Desktop.
class Namespace:
__slots__ = '_Namespace__names'
def __init__(self, **items):
self.__names = dict(**items)
def __setattr__(self, key, value):
if key in self.__slots__:
super().__setattr__(key, value)
else:
self.__names[key] = value
def __getattr__(self, item):
try:
return self.__names[item]
except KeyError:
raise AttributeError(item) from None
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.__names)
ns = Namespace()
ns.a1 = 'value a1'
ns.b1 = Namespace(b11='value b11')
ns.b1.b12 = 'value b12'
print(ns)
# -> Namespace({'b1': Namespace({'b12': 'value b12', 'b11': 'value b11'}), 'a1': 'value a1'})
pr1int(ns.a1)
# -> value a1
print(ns.b1.b11)
# -> value a1
print(ns.b1.b12)
# -> value a1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment