I have this method:
def filter_branches_by_names(self, names, exclude=False):
"""Filter branches list using names list.
Args:
names (list): names list to use as
filter condition.
exclude (bool): If set to False, keep branches in
names list. If set to True, keep branches not in names
list. Optional, default: False.
Returns:
branch (list): list of git branch objects.
"""
heads = self.repo.heads
if exclude:
return [head for head in heads if head.name not in names]
else:
return [head for head in heads if head.name in names]
It filters out branch objects that are accessed using gitPython
library. I do not know if that is something special with library (or it works for all objects), but when I use sorted
on result of that function, it actually does not sort those objects.
I mean this does not work:
sorted(self.filter_branches_by_names(['a', 'b'])
This works:
sorted(self.filter_branches_by_names(['a', 'b'], key=lambda x: x.name)
I'm using sorted for my unittests to check if I get correct branches when using that method, so I actually do not care how it is sorted, as long as both result and compared against lists are sorted the same.
So is sorted
intended to not sort objects (I thought it uses some kind of default parameter to sort by) when not specifying key
or it is something else here?
NOTE: I'm not saying I'm expecting it to sort by name
attribute. What I'm saying it does not sort at all, when not specifying key for sorted
. It seems people misunderstood me.
The base class object
defines all 6 rich comparison methods: __eq__
, __ge__
, __gt__
, and so on. These default methods compare by integer object identity, as returned by id(obj)
. For most purposes, one may consider ids to be random unique integers. Any class can define more appropriate comparison methods for instances of the class. It appears that the branch object class does not. My guess is that the authors of the class expect you to select an attribute for sorting.