Last active
December 11, 2015 13:18
-
-
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'
This file contains hidden or 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
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