Loop through List of strings to get form object attributes values

What I’m trying to do:
Loop through List of field names in my form to evaluate their text attributes

What I’ve tried and what’s not working:
I’m able to loop through the List and construct Strings representing the objects and the attributes I’m after, but I can’t actually evaluate these String representations. I get the error:

AttributeError: ‘str’ object has no attribute ‘text’

And since it appears that the eval() function isn’t supported, I can’t figure out how to pull in this info. In the code below, the error comes on the line: “thisFieldValue=thisFieldInput.text”

Code Sample:

  def validator(self):
    fieldTextList=['camperfirstname','camperlastname','parentname','parentemail','parentphone']
    for f in range(len(fieldTextList)):
      thisFieldInput='self.text_'+fieldTextList[f]
      thisFieldValue=thisFieldInput.text
      print (thisFieldInput)
      print (thisFieldValue)

Thank you.

Do you need to have them as a list of strings? If not, how about something like:

def validator(self):
    text_boxes = [
        self.text_camperfirstname,
        self.text_camperlastname,
        self.text_parentname,
        self.text_parentemail,
        self.text_parentphone,
    ]
    for text_box in text_boxes:
        print(text_box.text)

If you really need them as strings, you can use the getattr function:

def validator(self):
    field_names = [
        "camperfirstname",
        "camperlastname",
        "parentname",
        "parentemail",
        "parentphone",
    ]
    for field_name in field_names:
        text_box = getattr(self, f"text_{field_name}")
        print(text_box.text)
2 Likes

Thanks so much, Owen. The first option is the elegant option that I’ll use now but the second getattr option is the more versatile option that I’m sure I’ll use more often in the future. Thanks again.

1 Like