Created
July 22, 2015 16:09
-
-
Save jayd3e/ca48e32b927f2519ec27 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
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