Search code examples
pythonconfiginiconfigobj

ConfigObj: prevent writing empty sections


I'm using ConfigObj (5.0.6, both on python 2.7 and python 3.8) to manage my configs, but when I'm writing to file config with some sections only presented in configspec, they're appearing only as empty sections, which is not desired. I would appreciate any suggestions of fixing that behaviour of ConfigObj.

Minimal example of what happening:

from configobj import ConfigObj
from validate import Validator

spec = ["[Section]", "option = boolean(default=True)"]

config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
config.validate(Validator())
print(config)
print(config.write())

Output:

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False', '[Section]']

Desired output (there should be no empty sections when writing):

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False']

Edit 1: I'm using write() to actually write into file so I would prefer not just mess with returned list of strings


Solution

  • To put default values in the output config file, pass copy = True to the validate:

    from configobj import ConfigObj
    from validate import Validator
    
    spec = ["[Section]", "option = boolean(default=True)"]
    
    config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
    # set copy = True            vvvvvvvvvvv
    config.validate(Validator(), copy = True)
    print(config)
    print(config.write())
    

    which gives your desired output

    {'Section2': {'option2': False}, 'Section': {'option': True}}
    ['[Section2]', 'option2 = False', '[Section]', 'option = True']