Skip to content

Instantly share code, notes, and snippets.

@JackLeo
Last active December 11, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JackLeo/4606346 to your computer and use it in GitHub Desktop.
Save JackLeo/4606346 to your computer and use it in GitHub Desktop.
Converts configparser config to object with attributes relative to config For example config: [test] foo=bar will become: settings.TEST_FOO = 'bar'
import os
import ConfigParser
class Settings(object):
pass
def boolify(item):
return {'True': True, 'False': False}[item]
def autoconvert(item):
for method in (boolify, int, float):
try:
return method(item)
except:
pass
return item
def config2object(path, default_config):
config = ConfigParser.ConfigParser()
config.readfp(open(default_config)) # Read base cfg
if path:
config.read(os.path.expanduser(path)) # Read user cfg
settings = Settings()
for section in config.sections():
for item in config.items(section):
setattr(settings,
'%s_%s' % (section.upper(), item[0].upper()),
autoconvert(item[1]))
return settings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment