Search code examples
pythonclasssortingclass-method

Sorting a list of inherited class instances by a class attribute dictionary Key


Is it possible to write a base class method to sort a list of class objects, stored as a static class variable, in a child class, by a key in a dictionary, that is an attribute of the class using sort or sorted or does a more elaborate sorting method need to be written?

I’m a python noob and I’ve attempted to write the “my_sorter” method using sort & sorted, trying at a lambda key definition, itemgetter, and attrgetter and am not sure if I am failing at the syntax to access these mixed nested structures or if it’s just not possible without writing a more elaborate sorting routine to deliberately shift entries around in the list.

Note that each child class has a static variable named “mindex” that identifies the “primary key” of its attribute dictionary (i.e. a unique value to sort by). What would the my_sorter() method look like?

class Engine():
    storage = []

    @classmethod
    def my_sorter(cls):
        #sort cls.storage by cls.mindex

class Person(Engine):
    mindex = 'Name'

    def __init__(self, name):
        self.attributes = {
            'Name' : name,
        }

class Meeting (Engine):
    mindex = 'Date'

    def __init__(self, date):
        self.attributes = {
            'Date' : date,
        }

Solution

  • You don't show anywhere how your objects are ending up in the storage list, but assuming you have that working correctly (and you're not getting a mix of objects of different subclasses all in Engine.storage unexpectedly), the sorting should be pretty simple.

    @classmethod
    def my_sorter(cls):
        return sorted(cls.storage, key=lambda obj: obj.attributes[cls.mindex])
    

    I'm a little skeptical though about whether your Person and Meeting classes should be subclasses of Engine. That doesn't seem like an IS-A relationship to me. Perhaps it would make more sense if I knew the whole project design.