I have a Python dictionary that labels key name to attributes. The program that is tied to this dictionary is set to only have a few of the items, and only if they are necessary. So not all attributes in dictionary are defined at every pass of this script.
Here is the code with the dictionary
def getWidths(self,sheetName):
sheets = {
'dclabels':self.dclabels,
'tdclabels':self.tdclabels
}
sheetName = sheetName.lower()
if sheetName in sheets:
return sheets.get(sheetName)
else:
return self.colWidths
I am getting an error stating AttributError: ClassName instance has no attribute 'dclabels'
How can I avoid this error? Is there a way I can get the script to ignore any attributes that are not defined? Thanks!
I found a the solution to my issue.
def getWidths(self,sheetName):
if hasattr(self, sheetName.lower()):
name = getattr(self,sheetName.lower())
self.name = name
return self.name
else:
return self.colWidths
I made use of the hasattr()
and getattr()
to solve my problem. Thanks to all for your suggestions.