def sort(self, key=None, reverse=False, in_place=True): # no cmp argument to make sort more Python 3-like """Sorts the Hit objects. Arguments: key -- Function used to sort the Hit objects. reverse -- Boolean, whether to reverse the sorting or not. in_place -- Boolean, whether to perform sorting in place (in the same object) or not (creating a new object). `sort` defaults to sorting in-place, to mimick Python's `list.sort` method. If you set the `in_place` argument to False, it will treat return a new, sorted QueryResult object and keep the initial one unsorted. """ if key is None: # if reverse is True, reverse the hits if reverse: sorted_hits = list(self.hits)[::-1] # otherwise (default options) make a copy of the hits else: sorted_hits = list(self.hits)[:] else: sorted_hits = sorted(self.hits, key=key, reverse=reverse) # if sorting is in-place, don't create a new QueryResult object if in_place: new_hits = OrderedDict() for hit in sorted_hits: new_hits[self._hit_key_function(hit)] = hit self._items = new_hits # otherwise, return a new sorted QueryResult object else: obj = self.__class__(sorted_hits, self.id, self._hit_key_function) self._transfer_attrs(obj) return obj
def __init__(self, hits=[], id=None, hit_key_function=lambda hit: hit.id): """Initializes a QueryResult object. Arguments: id -- String of query sequence ID. hits -- Iterator returning Hit objects. hit_key_function -- Function to define hit keys, defaults to a function that return Hit object IDs. """ # default values self._id = id self._hit_key_function = hit_key_function self._items = OrderedDict() self._description = None self.program = '<unknown program>' self.target = '<unknown target>' self.version = '<unknown version>' # validate Hit objects and fill up self._items for hit in hits: # validation is handled by __setitem__ self.append(hit)