Skip to content

Instantly share code, notes, and snippets.

@evansde77
Created February 12, 2016 17:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evansde77/69e9af4f65687389b195 to your computer and use it in GitHub Desktop.
Save evansde77/69e9af4f65687389b195 to your computer and use it in GitHub Desktop.
Example of wrapping a nested JSON config object in a simple python object that allows dynamic object.attr style access to the data elements
#!/usr/bin/env python
"""
example of using a simple python object to wrap a JSON
configuration mapping so that it can be accessed as
a python style object using conf.attr1.attr2.value
"""
CONF = {
"CREDENTIALS": {
"SARNIE": {"password": "womp", "username": "derp"},
"JCOUNTS": {
"SUCCESS": {"success": True},
},
}
}
class ConfigMissing(Exception):
"""
Exception class to indicate a missing configuration element
"""
pass
class ConfigElement(object):
"""
object that uses __getattr__ to allow python object.name
style access to the dictionary that it wraps and
keeps track of nested names to allow for easier debugging
of missing configuration elements
"""
def __init__(self, conf_ref, name):
self.conf = conf_ref
self.name = name
def __repr__(self):
return "ConfigElement({})".format(self.name)
def __getattr__(self, name):
"""
override getattr to look for the name in
the configuration. If the element is a dictionary
then that is wrapped in a new ConfigElement instance
and returned.
If the element name is not found, a ConfigMissing
exception is raised, otherwise the value is returned
"""
new_name = ".".join([self.name, name])
conf_item = self.conf.get(name, ConfigMissing(new_name))
if isinstance(conf_item, dict):
return ConfigElement(conf_item, new_name)
if isinstance(conf_item, ConfigMissing):
raise conf_item
return conf_item
c = ConfigElement(CONF, 'CONF')
print c.CREDENTIALS
print c.CREDENTIALS.SARNIE
print c.CREDENTIALS.SARNIE.password
print c.CREDENTIALS.JCOUNTS.SUCCESS.success
print c.CREDENTIALS.JCOUNTS.SUCCESS.failure
@shaytangolova
Copy link

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment