Sorting list of objects on arbitrary attribute

Max M maxm at mxm.dk
Thu Jul 18 16:08:37 EDT 2002


Fredrik Lundh wrote:
> "Max M" wrote:

>>If something like it isn't included in the standard library, how come?

>     "It's easier to write appropriate code from scratch in Python
>     than to figure out how to *use* a package profligate enough
>     to contain canned solutions for all common and reasonable
>     use cases." -- tim peters


That's one side of the coin. The other one is that the standard library 
is like a common language, and the more of the language we share the 
easier it is to comunicate.

I just found that this particular kind of code keeps showing up in so 
many other peoples code that it might be usefull enough to have a common 
implementation.

Naturally there is a breaking point where something is general and 
usefull enough that it is worth adding to the library.

The way it is now I just have to figure out how to use every single 
implementation that somebody do in their own code.

Well it's not a big enough issue to raise a religious war over, I have 
made my own from scratch and will use that in my code ;-)

regards Max M


---------------------

Btw. I settled on this one instead:

-----------

class sortClass:

     """
     Sorts list on one or more attributes.
     If attribute is callable it sorts on the result
     """

     def __init__(self, attributes, ignoreCase=1):
         self.attributes = attributes # list of attribute names
         self.ignoreCase = ignoreCase # ignore case of strings if true

     def _attrList(self, obj):
         # creates list of rendered attributes
         attrList = []
         for attrName in self.attributes:
             attr = getattr(obj, attrName)
             if callable(attr):
                 attr = attr()
             if self.ignoreCase and type(attr) == type(''):
                 attr = attr.upper()
             attrList.append(attr)
         return attrList

     def __call__(self, obj1, obj2):
         return cmp(self._attrList(obj1), self._attrList(obj2))


if __name__ == '__main__':

     aList = SomeListWithObjects()
     sorter = sortClass(('name', 'age', 'rndNumber'))
     aList.sort(sorter)
     for item in aList:
         print item




More information about the Python-list mailing list