0

How do I set a Python class's attribute if I do not know at compile-time what attribute name will be (it gets read from a file with some redirection). I was hoping self[attrName]=attrvalue would work but I get the error Error 'ManifestReader' object does not support item assignment

Here is a minimum complete verifiable example (MCVE)

class ManifestReader(object):

    def Read(self):
        try:
            ### read a file here
            ### don't know attribute name at compile time
            ### so need to use self[attrName]=attrValue syntax
            attrName="foo"
            attrvalue="bar"
            self[attrName]=attrvalue

            ### above line causes the following error
            '''
            "Error 'ManifestReader' object does not support item assignment"
            "Press any key to continue . . ."           
            '''
        except Exception as e:
            print("Error " + str(e))


if __name__ == '__main__':
    rdr=ManifestReader()
    rdr.Read()

If there a better parent class I can inherit from?

S Meaden
  • 8,050
  • 3
  • 34
  • 65

2 Answers2

1

Use setattr:

setattr(self, attrName, attrvalue)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can use hasattr, setattr, getattr to do this.

if hasattr(obj, "attribute_name"):
     setattr(obj, "attribute_name", value)
Jmonsky
  • 1,519
  • 1
  • 9
  • 16