Last active
May 26, 2016 12:22
-
-
Save sirkonst/435f16adad834370044e to your computer and use it in GitHub Desktop.
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 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
Also see https://docs.python.org/3/library/types.html?highlight=simplenamespace#types.SimpleNamespace