Skip to content

Instantly share code, notes, and snippets.

@thomaswardiii
Created February 1, 2015 00:48
Show Gist options
  • Save thomaswardiii/0e49cc9425027a907ac7 to your computer and use it in GitHub Desktop.
Save thomaswardiii/0e49cc9425027a907ac7 to your computer and use it in GitHub Desktop.
ConfigParser with defaults and dictionary return
# Custom ConfigParser class
# Perhaps the defaults should be passed into this class for the purposes of others using this, but is scrubbed code from something
# I'll be using for my own purposes, and I wanted config stuff self-contained, and I'm still new to this so meh :)
import ConfigParser
class CustomConfigParser(ConfigParser.ConfigParser):
def __init__(self):
ConfigParser.ConfigParser.__init__(self)
# Change as necessary for your needs. Define all potential keys and their defaults here
self.defaults = {
'section1':
{
'foo': '',
'bar': '',
'baz': '',
},
'connection':
{
'hostname': 'example.com',
'port': '12345',
'username': 'guest',
'password': 'guest'
}
}
def as_dict(self):
config_data = {}
for ini_section_key in self.defaults:
config_data[ini_section_key] = {}
for ini_key, ini_value in self.defaults[ini_section_key].iteritem():
try:
config_data[ini_section_key][ini_key] = self.get(ini_section_key, ini_key)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
config_data[ini_section_key][ini_key] = ini_value
return config_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment