When using python ConfigParser, it is possible to read 2 files, such that it will combine both, and where the behaviour is that non-unique option values in later files over-write those in earlier files.

See e.g. https://stackoverflow.com/a/44266442/5020683

Consider the example given in that link, copied here for completeness (and all thanks to original author):

config1.ini:

[shared]
prop_uniue1 = 1
prop_shared = 10

[unique1]
test_unique = 101

config2.ini:

[shared]
prop_uniue2 = 2
prop_shared = 14

[unique2]
test_unique = 102


import ConfigParser

config = ConfigParser.ConfigParser()
config.read(['config1.ini', 'config2.ini'])


print config.sections() # ['shared', 'unique1', 'unique2']
print config.get("shared", "prop_uniue1")  # 1
print config.get("shared", "prop_shared")  # 14
print config.get("unique1", "test_unique") # 101

print config.get("shared", "prop_uniue2")  # 2
print config.get("unique2", "test_unique") # 102

Is it possible to configure config parser such that config2 can contain no unique options / sections, i.e. can only contain options already set in config1?

In the above example, I would like it to fail because config2 contains option prop_uniue2 which is not in config 1.

Use case:

config1 is defined to be a default config. config2 is a user supplied config, which can be used to overwrite the default config. This allows the user to specify only those options which need to be different from the default, and changes to the default propagate naturally (this behaviour is desired). config2 should not be able to specify any new options, to avoid the possibility that the user thinks they are overwriting an option but are not, due e.g. to a spelling mistake

1

There are 1 best solutions below

1
Gustavo F On

My way to do this is loading 2 .ini files and comparing them for differences:

import configparser

def readSections(config):
    for s in config.sections(): 
        for k in config.items(s):
            yield k[0]

configDefault = configparser.ConfigParser()
configDefault.read(['config1.ini'])

configUser = configparser.ConfigParser()
configUser.read(['config2.ini'])

for n in [item for item in readSections(configUser) if item not in readSections(configDefault)]:
    print(f'Error: {n} config is not defined on default .ini')

Output:

Error: prop_uniue2 config is not defined on default .ini