Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Comfortable config access with Python
#!/usr/bin/env python
import ConfigParser
import inspect
class DBConfig:
__doc__ = 'Collect a couple of config options in a type'
def __init__(self):
self.host = 'localhost' # You can also assign default values
self.dbname = None
def foo(self): pass
class ConfigProvider:
__doc__ = 'Interface which can copy values from ConfigParser into a config object'
def __init__(self, cfg):
self.cfg = cfg
def update(self, section, cfg):
__doc__ = 'Updates values in cfg with values from ConfigParser'
for name, value in inspect.getmembers(cfg):
if name[0:2] == '__' or inspect.ismethod(value):
continue
#print name
if self.cfg.has_option(section, name):
setattr(cfg, name, self.cfg.get(section, name))
class Main:
def __init__(self, dbConfig):
self.dbConfig = dbConfig
def run_me(self):
# And presto, we have a comfortable way to access config options
print('Connecting to %s:%s...' % (self.dbConfig.host, self.dbConfig.dbname))
# Create demo config
config = ConfigParser.RawConfigParser()
config.add_section('Demo')
#config.set('Demo', 'host', 'domain.com')
config.set('Demo', 'dbname', 'sample')
configProvider = ConfigProvider(config)
dbConfig = DBConfig()
# Magic happens here
configProvider.update('Demo', dbConfig)
main = Main(dbConfig)
main.run_me()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.