Skip to content Skip to sidebar Skip to footer

Define Order Of Config.ini Entries When Writing To File With Configparser?

I'm using the Python configparser to generate config.ini files to store my scripts configuration. The config is generated by code, but the point of the file is, to have an external

Solution 1:

The issue here is not that configparser isn't using OrderedDicts internally, it's that you're making an unordered literal and assigning that.

Notice how this is not ordered:

>>>x = {...'shuffle': 'True',...'augment': 'True',...# [... some other options ...] ...'data_layer_type' : 'hdf5',     ...'shape_img' : '[1024, 1024, 4]',    ...'shape_label' : '[1024, 1024, 1]', ...'shape_weights' : '[1024, 1024, 1]'...}>>>for k in x:...print(k)... 
shuffle
augment
shape_img
shape_label
shape_weights
data_layer_type

(This changes as an implementation detail in python3.6 as part of a "small dicts" optimization (all dicts become ordered) -- likely to be standardized as part of python3.7 due to convenience)

The fix here is to make sure you're assigning OrderedDicts all the way through:

config['DEFAULT'] = collections.OrderedDict((
    ('shuffle', 'True'),
    ('augment', 'True'),
    # [... some other options ...] 
    ('data_layer_type', 'hdf5'),     
    ('shape_img', '[1024, 1024, 4]'),    
    ('shape_label', '[1024, 1024, 1]'), 
    ('shape_weights', '[1024, 1024, 1]'), 
))

Solution 2:

The configparser seems to use OrderedDicts by default (since Python 2.7 / 3.1), which makes ConfigParser(dict_type=OrderedDict) obsolete. However this doesn't order entries by default, one still has to do that manually (at least in my case).

I found code to do that here and added ordering defaults as well:

import configparser
from collections import OrderedDict

# [...] define your config sections and set values here#Order the content of DEFAULT section alphabetically
config._defaults = OrderedDict(sorted(config._defaults.items(), key=lambda t: t[0]))

#Order the content of each section alphabeticallyfor section in config._sections:
    config._sections[section] = OrderedDict(sorted(config._sections[section].items(), key=lambda t: t[0]))

# Order all sections alphabetically
config._sections = OrderedDict(sorted(config._sections.items(), key=lambda t: t[0] ))

Post a Comment for "Define Order Of Config.ini Entries When Writing To File With Configparser?"