Skip to content

Instantly share code, notes, and snippets.

@humanium
Last active August 29, 2015 14:01
Show Gist options
  • Save humanium/f50c83a1f1c71d5dfcd0 to your computer and use it in GitHub Desktop.
Save humanium/f50c83a1f1c71d5dfcd0 to your computer and use it in GitHub Desktop.
dict to object (old version for history)
"""Module's functions allow convert Python dictionary to object.
"""
def dict2obj(pydict):
"""Converts dictionaries into objects that allow names
to be accessed as attributes as well as items.
"""
class container(object):
def __setitem__(self, key, value):
if not key.startswith('_'):
self.__dict__[key] = value
else:
msg = 'Key cannot start from underscores: "%s"' % key
raise AttributeError(msg)
def __getitem__(self, item):
if not item.startswith('_') and item in self.__dict__:
return self.__dict__[item]
else:
raise AttributeError('No such attribute: "%s"' % item)
def copy(obj):
if isinstance(obj, dict):
c = container()
for k, v in obj.iteritems():
c[k] = copy(v)
return c
elif isinstance(obj, (list, tuple)):
return [copy(i) for i in obj]
else:
return obj
return copy(pydict)
def yaml2obj(yamlfilename):
"""Converts information from file in YAML format to object
"""
import yaml
yt = yaml.loadfile(yamlfilename)
if not isinstance(yt, dict):
raise ValueError, '%s top level is not a dictionary' % yamlfilename
return dict2obj(yt)
##def dto2glob(pydict):
## """
## Converts dictionary to object
## and then loads it to module's namespace
## """
## globals().update(dict2obj(pydict))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment