Python's ConfigParser unique keys per section

前端 未结 2 576
花落未央
花落未央 2020-12-09 20:36

I read the part of the docs and saw that the ConfigParser returns a list of key/value pairs for the options within a section. I figured that keys did not need t

相关标签:
2条回答
  • 2020-12-09 21:03

    This deficiency of ConfigParser is the reason why pyglet used patched version of epydoc to replace ConfigParser ini with this simple format:

    name: pyglet
    url: http://www.pyglet.org/
    
    output: html
    target: doc/api/
    ...    
    module: pyglet
    
    exclude: pyglet.gl.gl
    exclude: pyglet.gl.agl
    exclude: pyglet.gl.lib_agl
    exclude: pyglet.gl.wgl
    ...
    

    If you don't need sections - this approach can be useful.

    0 讨论(0)
  • 2020-12-09 21:18

    ConfigParser isn't designed to handle such conditions. Furthermore, your config file doesn't make sense to me.

    ConfigParser gives you a dict-like structure for each section, so when you call parser.items(section), I'm expecting similar output to dict.items(), which is just a list of key/value tuples. I would never expect to see something like:

    [('spam', 'eggs'), ('spam', 'ham')]
    

    Not to mention, how would you expect the following to behave?:

    parser.get('Some Section', 'spam')
    

    Which is the intended way to retrieve values.

    If you want to store multiple values for the same key, I would suggest something like this in your config file:

    [Some Section]
    spam: eggs, ham
    

    And this in your code:

    spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')]
    

    Of course, this will only work for values that don't contain commas themselves or handle quoting. For that, you should employ a more advanced technique (see this and this).

    EDIT: If you don't mind the extra dependency, You could check out ConfigObj, which natively supports lists as a value type.

    0 讨论(0)
提交回复
热议问题