Skip to content

Instantly share code, notes, and snippets.

@jayd3e
Created July 22, 2015 16:09
Show Gist options
  • Save jayd3e/ca48e32b927f2519ec27 to your computer and use it in GitHub Desktop.
Save jayd3e/ca48e32b927f2519ec27 to your computer and use it in GitHub Desktop.
def dictify(variables):
# replace all dicts with AttrDicts
return {key: AttrDict(val) if isinstance(val, dict) else val for key, val in variables.items()}
class AttrDict(dict):
# only called if k not found in normal places
def __getattr__(self, k):
try:
# Throws exception if not in prototype chain
return self.return_attr_dict(object.__getattribute__(self, k))
except AttributeError:
try:
return self.return_attr_dict(self[k])
except KeyError:
raise AttributeError(k)
def return_attr_dict(self, val):
if isinstance(val, dict):
return AttrDict(val)
elif isinstance(val, (list, tuple)):
return type(val)(AttrDict(v) for v in val)
else:
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment