import re FILTER_RE = re.compile('[-[\]{}()*+?.,\\^$|#\s]') REPLACE_WITH = '' def filter_helper(object_list, attr, term): """ Helper method for filtering object_lists. @param object_list An array of objects to filter. @param attr An attribute on the object to filter the list by. @param term The filter term to look for in the attribute. @return The filtered list """ # remove special characters from the filter term escaped_term = FILTER_RE.sub(REPLACE_WITH, term) def compare(x): """ Function that compares the value to the filter term. @param x The object we are looking at. @return True if we have a match otherwise False. """ # get the attribute off the object v = getattr(x, attr) # attribute is a method so get the return value if callable(v): v = v() # remove special characters from the attribute value ev = FILTER_RE.sub(REPLACE_WITH, v) # if the term is an exact match or the escaped term is in the escaped attr if term == v or re.search(escaped_term, ev, re.I): return True return False # run the compare function through the list to create the filtered list return filter(compare, object_list)