diff --git a/deluge/config.py b/deluge/config.py index ed6c199b8..ff231691c 100644 --- a/deluge/config.py +++ b/deluge/config.py @@ -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 diff --git a/deluge/core/core.py b/deluge/core/core.py index f67c40ddf..2347f7786 100644 --- a/deluge/core/core.py +++ b/deluge/core/core.py @@ -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): diff --git a/deluge/tests/test_config.py b/deluge/tests/test_config.py index c329befc4..c8b07ffe4 100644 --- a/deluge/tests/test_config.py +++ b/deluge/tests/test_config.py @@ -31,9 +31,18 @@ class ConfigTestCase(unittest.TestCase): config["unicode"] = u"ВИДЕОФИЛЬМЫ" self.assertEquals(config["unicode"], u"ВИДЕОФИЛЬМЫ") - + 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)