Skip to content

Instantly share code, notes, and snippets.

@inizovtsev
Last active August 29, 2015 14:25
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 inizovtsev/aa2e85a80a6c1684e974 to your computer and use it in GitHub Desktop.
Save inizovtsev/aa2e85a80a6c1684e974 to your computer and use it in GitHub Desktop.
test = dict(
len=1,
objects=[
dict(foo='bar'),
dict(bar='baz'),
],
sub_object=dict(foo='bar')
)
def create_wrapper(assertion_f=None, list_index_suffix='_', dict_keys_suffix='_'):
def assertion(condition, message):
if not condition:
raise AssertionError(message)
if assertion_f is None:
assertion_f = assertion
def get_from_dict(obj, name):
alt_name = name
if name.startswith(dict_keys_suffix):
alt_name = name[len(dict_keys_suffix):]
assertion_f(name in obj or alt_name in obj, "key '{}' not found".format(name))
return obj.get(alt_name, obj.get(name))
def get_from_list(obj, name):
assertion_f(name.startswith(list_index_suffix), "list index should start with '{}'".format(list_index_suffix))
index = name[len(list_index_suffix):]
assertion_f(index.isdigit(), 'list index should be digit, not {}'.format(index))
index = int(index)
assertion_f(index < len(obj), "index {} is out of range ({})".format(index, len(obj)))
return obj[index]
class CollectionsWrapperMixin:
def __getattr__(self, name):
value = None
if isinstance(self, dict):
value = get_from_dict(self, name)
elif isinstance(self, list):
value = get_from_list(self, name)
if isinstance(value, dict):
value = wrappedDict(value)
elif isinstance(value, list):
value = wrappedList(value)
return value
wrappedDict = type('wrappedDict', (dict, CollectionsWrapperMixin), {})
wrappedList = type('wrappedList', (list, CollectionsWrapperMixin), {})
def wrap(obj):
if isinstance(obj, dict):
return wrappedDict(obj)
elif isinstance(obj, list):
return wrappedList(obj)
else:
raise Exception('object {} can not be wrapped'.format(obj))
return wrap
w = create_wrapper()(test)
print w.objects._1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment