Skip to content

Commit

Permalink
Add fallback option to ConfigUpdater.get
Browse files Browse the repository at this point in the history
This is closer to the API in ConfigParser
  • Loading branch information
abravalheri committed Aug 11, 2020
1 parent 6776dc6 commit 3182908
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/configupdater/configupdater.py
Expand Up @@ -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
Expand All @@ -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.
Expand Down
1 change: 1 addition & 0 deletions tests/test_configupdater.py
Expand Up @@ -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 = """
Expand Down

0 comments on commit 3182908

Please sign in to comment.