ConfigParser.get() defaults?

Tim Chase python.list at tim.thechases.com
Fri May 7 16:05:53 EDT 2010


With a normal dictionary, I can specify a default fallback value 
in the event the requested key isn't present:

   d = {}
   print d.get(42, 'Some default goes here')

However, with the ConfigParser object, there doesn't seem to be 
any way to do a similar

   cp = ConfigParser(...)
   # ...
   print cp.get('MySection', 'MyValue', 'Some default goes here')

that, in the event either "MySection" doesn't exist in the config 
file, or "MyValue" doesn't exist within "MySection", it simply & 
quietly returns my default.  At the moment, I have to mimic this with

   try:
     val = cp.get('MySection', 'MyValue')
   except (NoSectionError, NoOptionError), e:
     val = 'Some default goes here'
   print val

which is a real pain when you have multiple options, some using 
various combinations of get(), getboolean(), getint(), or 
getfloat().  Yes, I can write some cheap wrappers to do these, 
but it feels like something that should be built-in.


I've played with the DEFAULT, but that seems to just create its 
own section that I have to *ask* for:

   cp.get('DEFAULT', 'MyValue')



I've thumbed through the source to ConfigParser.py but don't see 
any indication that it's possible to do what I'd like short of 
wrapping all my cp.get*() calls in try/except blocks or creating 
a forked version of ConfigParser.py locally.  Is there anything 
I'm missing, or a better workaround to this?

Thanks,

-tkc






More information about the Python-list mailing list