diff --git a/src/configupdater/configupdater.py b/src/configupdater/configupdater.py index 1c621f4..9975f9b 100644 --- a/src/configupdater/configupdater.py +++ b/src/configupdater/configupdater.py @@ -975,12 +975,14 @@ def options(self, section): raise NoSectionError(section) from None return self.__getitem__(section).options() - def get(self, section, option): + def get(self, section, option, fallback=_UNSET): """Gets an option value for a given section. Args: section (str): section name option (str): option name + fallback: if the key is not found and fallback is provided, it will + be returned. ``None`` is a valid fallback value. Returns: :class:`Option`: Option object holding key/value pair @@ -991,11 +993,11 @@ def get(self, section, option): section = self.__getitem__(section) option = self.optionxform(option) try: - value = section[option] + return section[option] except KeyError: - raise NoOptionError(option, section) - - return value + if fallback is _UNSET: + raise NoOptionError(option, section) + return fallback def items(self, section=_UNSET): """Return a list of (name, value) tuples for options or sections. diff --git a/tests/test_configupdater.py b/tests/test_configupdater.py index 0ffcbbc..0e700be 100644 --- a/tests/test_configupdater.py +++ b/tests/test_configupdater.py @@ -206,6 +206,7 @@ def test_get_method(setup_cfg_path): updater.get('non_existent_section', 'license') with pytest.raises(NoOptionError): updater.get('metadata', 'wrong_key') + assert updater.get('metadata', 'wrong_key', fallback=None) is None test1_cfg_in = """