added config support for multiple sections

main
Fabien Benureau 12 years ago
parent f934e8c2ec
commit 45da61f4d2

@ -33,14 +33,18 @@ BOOLEANS = {'import-copy', 'import-move', 'color'}
# package-shared config that can be accessed using :
# from configs import config
_config = None
def config():
def config(section = MAIN_SECTION):
if config is None:
raise ValueError, 'not config instanciated yet'
_config._section = section
return _config
class Config(object):
def __init__(self):
object.__setattr__(self, '_cfg', configparser.SafeConfigParser(DFT_CONFIG))
self._cfg.add_section(MAIN_SECTION)
object.__setattr__(self, '_section', MAIN_SECTION) # active section
self._cfg.add_section(self._section)
def as_global(self):
global _config
@ -55,18 +59,21 @@ class Config(object):
self._cfg.write(f)
def __setattr__(self, name, value):
if type(value) is bool:
BOOLEANS.add(name)
self._cfg.set(MAIN_SECTION, name, str(value))
if name in ('_cfg', '_section'):
object.__setattr__(self, name, value)
else:
if type(value) is bool:
BOOLEANS.add(name)
self._cfg.set(self._section, name, str(value))
def __getattr__(self, name):
value = self._cfg.get(MAIN_SECTION, name)
value = self._cfg.get(self._section, name)
if name in BOOLEANS:
value = str2bool(value)
return value
def items(self):
for name, value in self._cfg.items(MAIN_SECTION):
for name, value in self._cfg.items(self._section):
if name in BOOLEANS:
value = str2bool(value)
yield name, value

@ -4,6 +4,7 @@ import unittest
import testenv
from papers import configs
from papers.configs import config
from papers.p3 import configparser
class TestConfig(unittest.TestCase):
@ -21,15 +22,16 @@ class TestConfig(unittest.TestCase):
def test_set(self):
a = configs.Config()
a.as_global()
from papers.configs import config
config().color = 'no'
self.assertEqual(config().color, False)
# booleans type for new variables are memorized, but not saved.
config().bla = True
self.assertEqual(config().bla, True)
with self.assertRaises(configparser.NoOptionError):
config()._cfg.get(configs.MAIN_SECTION, '_section')
def test_reload(self):
from papers.configs import config
a = configs.Config()
a.as_global()
@ -42,3 +44,14 @@ class TestConfig(unittest.TestCase):
b.as_global()
self.assertEqual(b, config())
self.assertEqual(config().color, configs.str2bool(configs.DFT_COLOR))
def test_exception(self):
a = configs.Config()
a.as_global()
with self.assertRaises(configparser.NoOptionError):
config().color2
with self.assertRaises(configparser.NoSectionError):
config(section = 'bla3').color
Loading…
Cancel
Save