Search code examples
pythonpython-2.7configobj

ConfigObj 'un-nest' sections


I'm using ConfigObj 5.0.6 to hold many user-defined values, some of which are nested. I use a local.ini to supercede typical values. There is no front-end, so users edit the configs as needed. To make that easier and more intuitive, there are some values that belong at the 'root' level of the config object, but are more easily understood below a nested section of the local.ini file.

I'm using a local.ini to supercede defaults. The flow of the app suggests a config layout that would have non-nested values below nested values.

# un-nested
title = my_title

# nested
[section_1]
val_s1 = val

[section_2]
val_s2 = val

# nested, but I want to be un-nested
val_2 = val

This layout, as expected, puts val_2 under section_2:

{
 'title': 'my_title',
 {'section_1': {'val_s1': 'val'}},
 {'section_2': {'val_s2': 'val'},
               {'val_2': 'val'}}
}

Is it possible to define val_2 on a line below section_2, but access it under the 'main' section of the config object?

I would like to end up with a config object like this:

{
 'title': 'my_title',
 {'section_1': {'val_s1': 'val'}},
 {'section_2': {'val_s2': 'val'}},
 'val_2': 'val'
}

The order of the config dictionary isn't important, of course; what I'm interested in is being able to use nested sections, but from within the .ini, exit a section into its parent.

I haven't tested, but suspect nesting everything from the first line onward and then slicing the config object would work. I.e., write local.ini such that it creates:

{
 'main_level':
  {
   'title': 'my_title',
   {'section_1': {'val_s1': 'val'}},
   {'section_2': {'val_s2': 'val'}},
   'val_2': 'val'
  }
}

Then I could use config = config['main_level'] when I first instantiate the config object, but I'm wondering if I'm just missing some easy, correct way that isn't a hack.


Solution

  • According to the documentation, that is not possible:

    In the outer section, single values can only appear before any sub-section.