I have a situation where I am going to have a lot of lists and the values in each of those lists need to be in some set of valid values. However the set of valid values is going to be different for each list. So before doing any appending to these lists I have to check for membership and that is making for a lot of repeated code. I'm finding myself tempted to extend the list object so that I wont have to do that membership check over and over.
class Attribute(list):
def __init__(self,validList):
self.valid = validList
def append(self,inString):
if inString not in self.valid:
raise Exception, '%s is not a valid value for this attribute' % inString
if inString not in self:
super(Attribute,self).append(inString)
That way I could have each of my lists with a different valid set of values. However, I feel like extending the built-in objects is not often a good idea and I have avoided it in the past. So my questions are
- Is there a built-in way to do this or is there a library that has something like this already?
- Is this a bad idea? What issues might arise from doing something like this?
Overriding append method after inheriting from a Python List was helpful in making this code work.