0

I would like to define several groups of values where the values of a particular group are used if that group is selected.

Here's a an example to make that clearer:

[environment]
type=prod

[prod]
folder=data/
debug=False

[dev]
folder=dev_data/
debug=True

Then to use it:

print config['folder'] # prints 'data/' because config['environment']=='prod'

Is there a natural or idiomatic way to do this in configobj or otherwise?


Additional Info

My current thoughts are overwriting or adding to the resulting config object using some logic post parsing the config file. However, this feels contrary to the nature of a config file, and feels like it would require somewhat complex logic to validate.

cammil
  • 9,499
  • 15
  • 55
  • 89

1 Answers1

0

I know this is maybe not exactly what you're searching for, but have you considered using json for easy nested access?

For example, if your config file looks like

{
    "environment": {
        "type": "prod"
    },
    "[dev]": {
        "debug": "True",
        "folder": "dev_data/"
    },
    "[prod]": {
        "debug": "False",
        "folder": "data/"
    }
}

you can access it with [dev] or [prod] key to get your folder:

>>> config = json.loads(config_data)
>>> config['[dev]']['folder']
'dev_data/'
>>> config['[prod]']['folder']
'data/'
adrianus
  • 3,141
  • 1
  • 22
  • 41
  • This is essentially possible in configobj. I just wanted to avoid `if config['environment']['type']=='prod'` everywhere in the code... – cammil Jul 21 '15 at 09:28
  • Oh, okay, I didn't know that. Then why not just switch config files, one for development and one for production? – adrianus Jul 21 '15 at 09:29
  • @cammil Or globally set (when initializing) the `config` variable to the list you want, either `[dev]` or `[prod]`... – adrianus Jul 21 '15 at 09:31
  • @cammil Did it work? In my last comment I meant setting `env = config['environment]['type']; config = config[env]` in the beginning of your code - one line to re-define the whole `config`-list to the environment specified in the beginning of your file. – adrianus Jul 22 '15 at 05:18
  • That is one solution but as mentioned in the question, I'm looking for a mechanism in configobj, or an idiomatic way to deal with what would seem like a common requirement – cammil Jul 22 '15 at 09:58