Skip to content

Instantly share code, notes, and snippets.

@tabdulradi
Last active December 10, 2015 10:48
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 tabdulradi/4423359 to your computer and use it in GitHub Desktop.
Save tabdulradi/4423359 to your computer and use it in GitHub Desktop.
Provides an adapter to allow using a class object in name-spacing your config constants conveniently . It allows you to use the dot notation to refer to your conf/constant, yet you can use features like key-word args unpacking too. It supports name-space inheritance from regular classes.
from collections import Mapping
from itertools import ifilter
class Namespace(Mapping):
'''
Provides an adapter to use a class as dict, and object at the same time.
It allows you to use the dot notation to refer to your conf/constant,
yet you can use features like key-word args unpacking too.
Use case:
class BaseNameSpace(object):
a = 0
@Namespace
class config(BaseNameSpace):
x = 1
@Namespace
class settings(object):
y = 2
z = 3
In [1]: conf.settings.z
Out[1]: 3
In [2]: dict(**conf.settings)
Out[2]: {'y': 2, 'z': 3}
In [3]: conf.a
Out[3]: 0
'''
def __init__(self, obj):
self.obj = obj
self.dct = {k:v
for C in reversed(obj.mro()[:-1]) # Skip object class
for k, v in C.__dict__.iteritems()
if not k.startswith('_') } # Skips keys starting with _
def __getitem__(self, key):
return self.dct[key]
def __getattr__(self, attr):
return getattr(self.obj, attr)
def __iter__(self):
return self.dct.__iter__()
def __len__(self):
return len(self.dct)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment