views:

508

answers:

2

Hi,

I want to map a INI file as a python object. So if the file have:

[UserOptions]
SampleFile = sample.txt
SamplePort = 80
SampleInt = 1
Sample = Aja
SampleDate = 10/02/2008

Then I want:

c = Configuration('sample.ini')

c.UserOptions.SamplePort = 90

I'm looking to setattr but I get a recursion error.

This is what I have:

class Configuration:
    def __init__ (self, fileName):
        cp = SafeConfigParser()
        cp.read(fileName)
        self.__parser = cp
        self.fileName = fileName

    def __getattr__ (self, name):
        if name in self.__parser.sections():
            return Section(name, self.__parser)
        else:
            return None

    def __str__ (self):
        p = self.__parser
        result = []
        result.append('<Configuration from %s>' % self.fileName)
        for s in p.sections():
            result.append('[%s]' % s)
            for o in p.options(s):
                result.append('%s=%s' % (o, p.get(s, o)))
        return '\n'.join(result)

class Section:
    def __init__ (self, name, parser):
        self.__name = name
        self.__parser = parser

    def __getattr__ (self, name):
        if self.__dict__.has_key(name):       # any normal attributes are handled normally
            return __getattr__(self, item)
        else:
            return self.__parser.get(self.name, name)

    def __setattr__(self, item, value):
        """Maps attributes to values.
        Only if we are initialised
        """
        if self.__dict__.has_key(item):       # any normal attributes are handled normally
            dict.__setattr__(self, item, value)
        else:
            self.__parser.set('UserOptions',item, value)

Now I wonder why in self.__parser.set('UserOptions',item, value) I get the error. I read in the pythons docs and I don't get what to do. I suspect that I need store a dict with the fields name and first look there but how?

+4  A: 

You are trying to get the sections on request. But it is much easier to iterate over sections and options and add them as attribute in __init__. I edited my example to support setattr as well. You problem is explained here you are assigning the attributes in __setattr__ while you should use __dict__ instead

from ConfigParser import  SafeConfigParser

class Section:
    def __init__(self, name, parser):
        self.__dict__['name'] = name
        self.__dict__['parser'] = parser

    def __setattr__(self, attr, value):
        self.__dict__[attr] = str(value)
        self.parser.set(self.name, attr, str(value))

class Configuration(object):
    def __init__(self, fileName):
        self.__parser = SafeConfigParser()
        self.__parser.read(fileName)
        self.fileName = fileName
        for section in self.__parser.sections():
            setattr(self, section, Section(section, self.__parser))
            for option in self.__parser.options(section):
                setattr(getattr(self, section), option,
                        self.__parser.get(section, option))

    def __getattr__(self, attr):
        self.__parser.add_section(attr)
        setattr(self, attr, Section(attr, self.__parser))
        return getattr(self, attr)

    def save(self):
        f = open(self.fileName, 'w')
        self.__parser.write(f)
        f.close()

c = Configuration('config.ini')

print dir(c) -> will print all sections
print dir(c.UserOptions) -> will print all user options
print c.UserOptions.sampledate

c.new.value = 10
c.save()
Nadia Alramli
Really Quite Nice.
Sanjaya R
The OP was using ConfigParser as well (just forgot to include the import).
dF
+3  A: 

Your problem is in Section.__init__. When you set self.__name = name it calls your __setattr__ method, doesn't find the key in __dict__ so it goes to

 self.__parser.set('UserOptions',item, value)

So now it needs self.__parser.

Which hasn't been set yet. So it tries to get it using __getattr__. Which sends it looking for self.__parser. Which hasn't been set yet. So it tries to get it using __getattr__. So... you get the point :-)

One way to avoid this is by adding a condition in Section.__setattr__ like this

if item.startswith('_') or self.__dict__.has_key(item):
   ^^^^^^^^^^^^^^^^^^^^^^^
   ...

which will make sure __name and __parser are set properly on initialization.

dF
Auch!Thanks for the input.
mamcx