Refreshing or re-running a class in Python 2.7
Question: I have a class that retrieves values from a configuration file and a function
that adds them. I call the class, change values then run the function to write
them. When I call the class afterwards the values are not updated. I check the
config file and the values have changed. Is there a way to get it to re-read
the data every time I call it?

Heres a simplified version...

    
    
    import ConfigParser
    
    class read_conf_values():
        parser = ConfigParser.ConfigParser()
        parser.read('configuration.conf')
        a = parser.get('asection', 'a')
    
    
    def confwrite(newconfig):
        file = open("configuration.conf", "w")
        file.write(newconfig)
        file.close()
    
    conf = read_conf_values()
    print conf.a
    newvalue = raw_input('Enter a new value for a?')
    newconfig = '[asection]\na = '+newvalue
    confwrite(newconfig)
    conf = read_conf_values()
    print conf.a
    

I have to write the file instead of using configparser to add values as the
actual configuration doesn't have sections. I can read it with a fake section
module but I have to write it like a text file. This example has the same
problem though.


Answer: Your `a` is a class attribute, so it is only created once, at the time you
define the class. Do this instead:

    
    
    class read_conf_values(object):
        def __init__(self):
            parser = ConfigParser.ConfigParser()
            parser.read('configuration.conf')
            self.a = parser.get('asection', 'a')
    

Then a new `a` attribute will be set every time you create an instance (with
`read_conf_values()`). You can find many, many other questions on this site
about the difference between class and instance attributes.

