ConfigParser.get() defaults?
Jon Clements
joncle at googlemail.com
Fri May 7 17:46:26 EDT 2010
On 7 May, 21:05, Tim Chase <python.l... at tim.thechases.com> wrote:
> 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
Not convinced about this, but a quick "work-around" would be something
like:
def get_config(config, section, option, ctype=str, default=None):
if default is None:
ret = config.get(section, option)
else:
confdict = config.__dict__.get('_sections')
ret = confdict.get(section).get(option, default)
return ctype(ret)
That should cover most exceptions and the get* functions..., just
provide your own factory function to post-parse it...
Of course, I'm probably missing something as usual...
Anyway, Cheers,
Jon.
More information about the Python-list
mailing list