Add a get method to config so a default value can be returned
This commit is contained in:
parent
daba92b992
commit
b6a3161280
|
@ -268,6 +268,32 @@ what is currently in the config and it could not convert the value
|
|||
else:
|
||||
return self.__config[key]
|
||||
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
Gets the value of item 'key' if key is in the config, else default.
|
||||
If default is not given, it defaults to None, so that this method
|
||||
never raises a KeyError.
|
||||
|
||||
:param key: the item for which you want it's value
|
||||
:param default: the default value if key is missing
|
||||
:return: the value of item 'key' or default
|
||||
|
||||
**Usage**
|
||||
|
||||
>>> config = Config("test.conf", defaults={"test": 5})
|
||||
>>> config.get("test", 10)
|
||||
5
|
||||
>>> config.get("bad_key", 10)
|
||||
10
|
||||
|
||||
"""
|
||||
try:
|
||||
return self.get_item(key)
|
||||
except KeyError:
|
||||
return default
|
||||
|
||||
|
||||
def __delitem__(self, key):
|
||||
"""
|
||||
See
|
||||
|
|
|
@ -480,23 +480,12 @@ class Core(component.Component):
|
|||
@export
|
||||
def get_config_value(self, key):
|
||||
"""Get the config value for key"""
|
||||
try:
|
||||
value = self.config[key]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
return value
|
||||
return self.config.get(key)
|
||||
|
||||
@export
|
||||
def get_config_values(self, keys):
|
||||
"""Get the config values for the entered keys"""
|
||||
config = {}
|
||||
for key in keys:
|
||||
try:
|
||||
config[key] = self.config[key]
|
||||
except KeyError:
|
||||
pass
|
||||
return config
|
||||
return {(key, self.config.get(key)) for key in keys}
|
||||
|
||||
@export
|
||||
def set_config(self, config):
|
||||
|
|
|
@ -34,6 +34,15 @@ class ConfigTestCase(unittest.TestCase):
|
|||
|
||||
config._save_timer.cancel()
|
||||
|
||||
def test_get(self):
|
||||
config = Config("test.conf", config_dir=self.config_dir)
|
||||
config["foo"] = 1
|
||||
self.assertEquals(config.get("foo"), 1)
|
||||
self.assertEquals(config.get("foobar"), None)
|
||||
self.assertEquals(config.get("foobar", 2), 2)
|
||||
config["foobar"] = 5
|
||||
self.assertEquals(config.get("foobar", 2), 5)
|
||||
|
||||
def test_load(self):
|
||||
def check_config():
|
||||
config = Config("test.conf", config_dir=self.config_dir)
|
||||
|
|
Loading…
Reference in New Issue