Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigObj/ConfigParser vs. using YAML for Python settings file

Which is better for creating a settings file for Python programs, the built-in module (ConfigParser) or the independent project (ConfigObj), or using the YAML data serialization format? I have heard that ConfigObj is easier to use than ConfigParser, even though it is not a built-in library. I have also read that PyYAML is easy to use, though YAML takes a bit of time to use. Ease of implementation aside, which is the best option for creating a settings/configuration file?

like image 477
Apophenia Overload Avatar asked Aug 09 '10 21:08

Apophenia Overload


People also ask

What is ConfigParser used for in Python?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

Does ConfigParser come with Python?

configparser comes from Python 3 and as such it works well with Unicode.

How use config YAML file in Python?

Reading a key from YAML config file We can read the data using yaml. load() method which takes file pointer and Loader as parameters. FullLoader handles the conversion from YAML scalar values to the Python dictionary. The index [0] is used to select the tag we want to read.


1 Answers

It depends on what you want to store in your config files and how you use them

  • If you do round tripping (yaml→code→yaml) and want comments preserved you cannot use PyYAML or ConfigParser.

  • If you want to preserve the order of your keys (e.g. when you check in your config files), PyYAML doesn't do that unless you specify !!omap (which makes it less easy to update than a normal mapping)

  • If you want to have complex structures with lists of unnamed elements containing mappings/dictionaries, then ConfigParser and ConfigObj won't help you as the INI files key-value pairs have to go into sections and lists can only be values.

The ruamel.yaml implementation of the YAML reader supports all of the above ¹. I have used fuzzyman's excellent ConfigObj for round trip comment preservation for a long time, as well as PyYAML for more complex structures and this combines best of both worlds. ruamel.yaml includes the yaml utility that can convert ConfigObj INI files to YAML


¹ ruamel.yaml is a YAML library that supports YAML 1.2 (I recommend using that, but then I am the author of the package). PyYAML only supports (most of) YAML 1.1.

like image 173
Anthon Avatar answered Sep 30 '22 02:09

Anthon