Most Pythonic way to store (small) configuration

Rustom Mody rustompmody at gmail.com
Thu Aug 6 03:01:35 CEST 2015


On Thursday, August 6, 2015 at 2:31:52 AM UTC+5:30, Tim Chase wrote:
> On 2015-08-05 06:37, Rustom Mody wrote:
> > >   config = {}
> > >   with open('config.ini') as f:
> > >     for row in f:
> > >       row = row.strip()
> > >       if not row or row.startswith(('#', ';')):
> > >         continue
> > >       k, _, v = row.partition('=')
> > >       config[k.strip().upper()] = v.lstrip()
> > > 
> > > which is pretty straight-forward and easy format to edit.
> > > 
> > > -tkc  
> > 
> > JSON handles basic types like this:
> > >>> from json import loads
> > >>> loads("""{"anInt":1, "aString":"2"}""")  
> > {'aString': '2', 'anInt': 1}
> 
> But requires the person hand-editing the file to make sure that
> opening braces close, that quoted text is properly opened/closed, has
> peculiarities regarding things following back-slashes, etc.
> 
> There's a certain simplicity to simply having key/value pairs
> separated by an "=" and then letting the application do whatever it
> needs/wants with those key/value strings.
> 
> -tkc

I just checked that literal_eval accepts comments.
So thats one plus for that.
However I must admit that in checking that out I was faced with more than
(I) expected unfriendly error messages like

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python3.4/ast.py", line 62, in _convert
    in zip(node.keys, node.values))
  File "/usr/lib/python3.4/ast.py", line 61, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/usr/lib/python3.4/ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x7fe1173ebac8>


By contrast here is a more friendly error message (had put a comma where a colon
required)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib/python3.4/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 2
    "i", 1}

So overall whether ast.literal_eval is a good idea is not clear to me


More information about the Python-list mailing list