From b6a316128050a04dfa9fc486b5e0d1f19c0c27dc Mon Sep 17 00:00:00 2001 From: Calum Lind Date: Thu, 9 May 2013 18:41:30 +0100 Subject: [PATCH] Add a get method to config so a default value can be returned --- deluge/config.py | 26 ++++++++++++++++++++++++++ deluge/core/core.py | 15 ++------------- deluge/tests/test_config.py | 11 ++++++++++- 3 files changed, 38 insertions(+), 14 deletions(-) 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)