dynamic setattr

Mariano Di Felice mariano.difelice at gmail.com
Fri Jul 27 08:49:45 EDT 2012


Hi, 
  I have a property file (.ini) that has multiple sections and relative keys, as default structure.

Now, I would like to export from my utility class methods getter and setter.
I have started as is:

class Utility:

  keys = {"STANDUP": ["st_key1", "st_key2", "st_key3", "st_key4"],
              "DEFAULT": ["def_key1", "def_key2", "def_key3", "def_key4", "def_key5"]}


  def __init__(self):
            for section, keyList in  keys .items():
            for key in keyList:
                setattr(self, "get_%s" % key, self.get_value(section, key))
                setattr(self, "set_%s" % key, lambda value:self.set_value(section, key, value) )

  def get_value(section, key):
        if file_ini.has_option(section, key):
            return lambda: file_ini.get(section, key)
        return lambda: None

  def set_value(section, key, value):
        print "set section: %s - key: %s - value: %s" % (section, key, value)
        if file_ini.has_option(section, key):
            file_ini.set(section , key ,value)


if __name__ == "__main__":
  utility = Utility()
    print "key2: %s" % utility.get_def_key2() ## -> value return 100
    print "set value 50 to def_key2"
    utility.set_def_key2(50)
    print "new value def_key2: %s" % utility.get_def_key2()  ## -> value return 100


Well, when in code I set value 50 to def_key2, return value of key st_key4 of STANDUP section!!!! Why?
"set section STANDUP - key st_key4 - value: 200"

Can anyone help me, please???

Thx in Advance



More information about the Python-list mailing list