Home > Blockchain >  Does ConfigParser preserve the order of sections from file?
Does ConfigParser preserve the order of sections from file?

Time:10-31

The order of the sections in my INI file is important.

Apparently, when I use ConfigParser.sections(), the order of sections in the returned list is the same as in the file. But is this guaranteed? I couldn't find this detail in documentation.

If not, what is the best approach to informing the order of sections?

Example:

import configparser

ini_file= """
[Section 1]
option = value

[Section 2]
another = val
"""

config = configparser.ConfigParser()
config.read_string(ini_file)
config.sections()

The return value I get is ['Section 1', 'Section 2']. Is this always the case?

CodePudding user response:

Yes, because the sections are added to an internal dictionary as the file is being read line by line. As of Python version 3.7, dictionaries are ordered, therefore the sections should be in the order you define them in the config file.

Inspecting the source code of configparser, you can see the sections are stored inside self._dict:

Which is a standard Python dict object:

  • Related