Skip to content

Instantly share code, notes, and snippets.

@lqc
Created February 25, 2011 18:16
Show Gist options
  • Save lqc/844222 to your computer and use it in GitHub Desktop.
Save lqc/844222 to your computer and use it in GitHub Desktop.
from ConfigParser import RawConfigParser, NoOptionError
class SectionProxy(object):
__slots__ = ('_section_name', '_config')
def __init__(self, config, section_name):
self._section_name = section_name
self._config = config
def __getattr__(self, name):
try:
return self._config.get(self._section_name, name)
except NoOptionError:
raise AttributeError("No option %r in section %r" % (self._section_name, name))
class Config(object):
"""
Object to store configuration. You can access
config items using normal attribute lookup
>>> from StringIO import StringIO
>>> config = Config(StringIO(SAMPLE_CONFIG))
>>> config._config.get("section1", "a")
'10'
>>> config.section1.a
'10'
>>> config.section2.b
'ala'
>>> hasattr(config, "section3")
False
>>> hasattr(config.section1, "invalid")
False
"""
def __init__(self, config_file):
self._config = RawConfigParser()
self._config.readfp(config_file)
def __getattr__(self, name):
if self._config.has_section(name):
return SectionProxy(self._config, name)
raise AttributeError("No config section %r" % name)
if __name__ == "__main__":
import doctest
SAMPLE_CONFIG = """
[section1]
a = 10
[section2]
b = ala
"""
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment