Herbie icon indicating copy to clipboard operation
Herbie copied to clipboard

Improve config file usage

Open blaylockbk opened this issue 1 year ago • 1 comments

I would like to make changes to the way the config file is used, like as the ability to change the config values temporarily (adjust the defaults inside a single script)

Here is what ChatGPT says I could do:


To allow a user to temporarily update config attributes without modifying the config file, you can modify the Config class to store the temporary updates in a separate dictionary. Here's an example of how you can do this:

class Config:
    def __init__(self, config_file):
        self.config_file = config_file
        self.config = {}
        self.temp_updates = {}
        with open(self.config_file, 'r') as f:
            for line in f:
                key, value = line.strip().split('=')
                self.config[key] = value

    def get(self, key):
        if key in self.temp_updates:
            return self.temp_updates[key]
        return self.config[key]

    def set(self, key, value, temporary=False):
        if temporary:
            self.temp_updates[key] = value
        else:
            self.config[key] = value
            with open(self.config_file, 'w') as f:
                for k, v in self.config.items():
                    f.write(f'{k}={v}\n')

    def reset(self):
        self.temp_updates = {}

With this modified Config class, you can use the set method to temporarily update a config value by setting the temporary argument to True. The temporary update will be stored in the temp_updates dictionary, and the get method will return the temporary value if it exists.

To reset all temporary updates and restore the original config values, you can use the reset method. This will clear the temp_updates dictionary.

Here's an example of how you might use these new methods:

# Load the config file
config = Config('/path/to/config.txt')

# Get the original value of a config key
value = config.get('key')

# Temporarily update the value of the key
config.set('key', 'new_value', temporary=True)

# Get the temporary updated value of the key
temp_value = config.get('key')

# Reset the temporary updates and restore the original value
config.reset()

# Get the original value of the key again
value = config.get('key')


There, that might give you a starting place.

blaylockbk avatar Dec 24 '22 21:12 blaylockbk