[issue8666] Allow ConfigParser.get*() to take a default value

Tim Chase report at bugs.python.org
Mon May 10 02:51:26 CEST 2010


Tim Chase <python.list at tim.thechases.com> added the comment:

Yes, the use-case is the same as a dict.get(key, default) which I frequently use -- so it can be used in things like

  result = some_function(
     cp.get('MySection', 'MyValue', default='hello'),
     cp.getint('MySection', 'MyInt', default=42)
     )

To write something similar with the current ConfigParser requires a lot more code or an inelegant wrapper (either passing the config-parser object each call, or capturing the parser object in a closure which makes the "def" something repeated):

  try:
    mv = cp.get('MySection', 'MyValue')
  except (NoSectionError, NoOptionError), e:
    mv = 'hello'
  try:
    mi = cp.getint('MySection', 'MyInt')
  except (NoSectionError, NoOptionError), e:
    mi = 42
  result = some_function(mv, mi)
  del mv, mi  # leaving the namespace as it was before

The above can be done in a scattering of wrapper functions, but the addition in stock ConfigParser prevents a lot of duplicate code.  This is the fourth project in which I've used the ConfigParser and have reached for a default value in every one of them, to be frustrated by the lack.

The old-style "raise ValueError" you mention was the original code (just indented), but I've changed it to the preferred format.

For the dangling close-paren or "):" on its own line, I tend to do it for the same reason a trailing comma is allowed/encouraged in lists/tuples/dicts/param lists, so it's easy to add further comma-separated entries without giving cluttered diffs.  The source against which I'm patching has several dangling close-parens already (search for "^\s*)" to find the calls to re.compile).

I pulled down the branches/py3k and patched against it. (attached)

----------
Added file: http://bugs.python.org/file17280/configparser.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8666>
_______________________________________


More information about the Python-bugs-list mailing list