tags:

views:

1059

answers:

4

Hi! The typical ConfigParser generated file looks like:

[Section]
bar=foo
[Section 2]
bar2= baz

Now, is there a way to index lists like, for instance:

[Section 3]
barList={
    item1,
    item2
}

Related question: Python’s ConfigParser unique keys per section

? Thanks in advance

+1  A: 

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

M. Utku ALTINKAYA
thanks for the clarification, utku. the only problem is that i can't use external packages at the moment. i think i'm gonna write a simple class to handle this. i'll share it eventually.
pistacchio
What version of Python are you running? The JSON module is included with 2.6.
Patrick Harrington
+4  A: 

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not prety but it's functional for most simple lists.

David Locke
That's the way the Python logging config file works.
S.Lott
And if you've got complex lists, you can refer to this question: http://stackoverflow.com/questions/330900/how-to-quickly-parse-a-list-of-strings :-)
John Fouhy
+1  A: 

I faced the same problem in the past. If you need more complex lists, consider creating your own parser by inheriting from ConfigParser. Then you would overwrite the get method with that:

    def get(self, section, option):
    """ Get a parameter
    if the returning value is a list, convert string value to a python list"""
    value = SafeConfigParser.get(self, section, option)
    if (value[0] == "[") and (value[-1] == "]"):
        return eval(value)
    else:
        return value

With this solution you will also be able to define dictionaries in your config file.

But be careful! This is not as safe: this means anyone could run code through your config file. If security is not an issue in your project, I would consider using directly python classes as config files. The following is much more powerful and expendable than a ConfigParser file:

class Section
    bar = foo
class Section2
    bar2 = baz
class Section3
    barList=[ item1, item2 ]
Mapad
A: 

This is essentially the same question.

Jeremy Cantrell