Search code examples
pythonconfigurationconfigconfigureconfigparser

Python: Using ConfigParser vs json file


I am currently using the ConfigParser module to read and parse the configuration for a python program. I understand that using ConfigParser streamlines the parsing and reading of configuration from file, however I am just curious as to what would be the tradeoffs if I simply use a json format for reading/writing config files. Wouldn't that be equally easy to parse etc, same as ConfigParser ?


Solution

  • JSON would be easy enough for your program to parse, but it would also burden the user with the responsibility of getting braces and quotes just right, and it would add unnecessary clutter to your configuration files. If that extra complexity is okay with you, or if you really need the kind of deep nesting that is slightly easier to parse in JSON than in flat config files, then by all means, use JSON. Some people even take this a step further and put their configuration in Python files.

    Personally, I feel that configuration files that users might need to read or edit should be as simple as possible, so I use (a subset of) the configparser syntax. If I need hierarchy, I simply represent it with dots:

    parent.child1 = foo
    parent.child2 = bar
    

    When I want to avoid requiring [sections] in my config files, I can either trick configparser into not needing them, or use a TOML parser instead.