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:
var_list = ['var1', 'var2', 'var3'] # create list of variable string names
for var in var_list: # iterate over list of variable names
try:
# use exec to execute assignments, assuming attribute exists
exec('{0} = {1}'.format(var, getattr(self, var)))
except AttributeError: # catch the Exception if the attribute does not exist
exec('{0} = None'.format(var)) # set var to some default value, whatever
# is convenient for later code to check
# for and handle
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.