Most Pythonic way to store (small) configuration

Cameron Simpson cs at zip.com.au
Mon Aug 3 00:49:30 CEST 2015


On 02Aug2015 18:51, Cecil Westerhof <Cecil at decebal.nl> wrote:
>On Sunday  2 Aug 2015 13:54 CEST, Ben Finney wrote:
>> Cecil Westerhof <Cecil at decebal.nl> writes:
>>> Because of this I think a human readable file would be best.
>>
>> I agree with that criterion; in the absence of compelling reasons
>> otherwise, human-readable and -editable text is a good default.
[...]
>> The “INI” format as handled by the Python ‘configparser’ module is
>> what I would recommend for a simple flat configuration file. It is
>> more intuitive to edit, and has a conventional commenting format.
>
>Well, I would use nested data. (A file will have extra fields besides
>the name.) That is why I was thinking about json. But I will look into
>it.

Like others, I also recommend an INI file. You can always move to something 
more complex (and harder to edit) if it doesn't work out.

Note that "nested data" does not rule out an INI file unless you mean 
"recursive" data or quite a deep nesting of structure. Shallow structure (one 
or two levels) is very easy to embed in the INI format.

Eg:

  [main]
  this = that
  size = 10
  directory = /path/to/default/dir

  [gui]
  foreground = green
  style = baroque

  [*.log]
  stuff about log files...

  [/path/to/file1]
  title = something
  param1 = 5
  param2 = 6
  fields = column2, column7

  [column2:/path/to/file1]
  format = numeric
  scale = logarithmic

  [column7:/path/to/file1]
  format = roman
  scale = linear

See that by being a little tricky about the section names you can incorporate a 
fair degree of structure? I would not advocating going too fair down that 
rabbit hole, but for basic stuff it works well.

And of course you can put structure within a section:

  [foo]
  complexity = {'blah': 'blah blah', 'frib': {'frob': 1, 'frab': 2}}
  format_width = 10
  format_style = right-justified
  format_dialect = quoted

i.e. you could put (small) JSON snippet in some fields, or present a few 
parameters to describe "format".

There are several ways to do this kind of thing before reaching for more 
complex syntaxes. Just don't let it get too weird - that would probably be a 
sign you do want to reach for JSON or YAML.

But start with INI. Simple and easy.

Cheers,
Cameron Simpson <cs at zip.com.au>

A squealing tire is a happy tire.
        - Bruce MacInnes, Skip Barber Driving School instructor


More information about the Python-list mailing list