Home > Software engineering >  Readonly configuration variables ini file
Readonly configuration variables ini file

Time:02-11

I have a program in python that has an ini file with the configuration variables for the program. Some variables are ReadWrite and others ReadOnly.

My config file is something like this:

[AuthCtrlr]
enable = True
nbrOfMssgs = 10

where I want the variable enable to be ReadWrite and nbrOfMssgs ReadOnly.

In my python code, I can change my variables with:

parser.set('AuthCtrlr', 'enable', False)

with the configparser module.

Is there a way to make a code where if I want to change the variable nbrOfMssgs it prints something like "This variable is ReadOnly" and don't change the value of the variable?

CodePudding user response:

import configparser

class wrappedParser(configparser.ConfigParser):
    def __init__(self):
        super().__init__()
        self.readOnlySettings = []
    def set(self, category, setting, value):
        if setting in self.readOnlySettings:
            raise PermissionError(f"{setting} setting is read-only")
        else:
            return super().set(category, setting, value)
    def makeReadOnly(self, setting):
        self.readOnlySettings.append(setting)



config = wrappedParser()
config['bitbucket.org'] = {}
config.set('bitbucket.org', 'User', 'hg')
config.makeReadOnly('User')
try:
    config.set('bitbucket.org', 'User', 'pg')
except PermissionError as err:
    print(err)
print(config.get('bitbucket.org', 'User'))

Make a child class inheriting from ConfigParser that reimplements set operation in a way that raises an error if the setting you are trying to change is one of the read-only ones.

Still, this does not in any way improve security of your code. It's only good to prevent you from accidentially changing the settings. Which asks the question, why would that happen?

  • Related