I have a long list of if statements that are checking if an object (self) contains a series of optional attributes.
As an example:
if(hasattr(self, variableList)):
var1 = self.var1
if(hasattr(self, "var2")):
var2 = self.var2
if(hasattr(self, "var3")):
var3 = self.var3
if(hasAttr(self, "var4")):
var4 = self.var4
I was trying to figure out if there was a simple way of using a for loop that would use variable names from a list to check the object, and if they exist to store them locally in the method, which I think would require a dictionary in some way. Is it bad practice to try the above? Would it be more appropiate to have the more explicit list or to reduce the code with something like
for x in variableList:
if(hasattr(self,variableList[x]))
localvariable = variableList[x]
This should work for you:
As others suggested in the comments, you seem to be using an odd construct. After you get your code working, I would suggest taking it over to CodeReview and ask about better methods to achieve what you're trying to do. Without seeing the rest of your code it's hard to tell, but I suspect there's a better way to accomplish your overall goal.