Can I pass variables to the compare function in sorted method in Python?

Question:

Here is the code:

    if(order=="dsc"):
        return sorted(qs, key=compare_function, reverse=True)
    elif (order=="asc"): # asc
        # return sorted(qs, key=lambda obj: obj.teacher.name)
        return sorted(qs, key=compare_function)
    else:
        pass



def compare_function(obj):

    if obj == None:     
        return "aaaaaaa"
    if obj.teacher == None: 
        return "aaaaaaa"
    else:   
        test = {"teacher": obj.teacher}
        return test.get("teacher").name.lower()
    

What I expect is to pass some additional params to compare_function like below:

    if(order=="dsc"):
        return sorted(qs, key=compare_function(cls_name), reverse=True)
    elif (order=="asc"): # asc
        # return sorted(qs, key=lambda obj: obj.teacher.name)
        return sorted(qs, key=compare_function(cls_name))
    else:
        pass

    def compare_function(obj, cls_name):
        if obj == None:     
            return "aaaaaaa"
        if obj.teacher == None: 
            return "aaaaaaa"
        else:   
            test = {"teacher": obj.teacher}
            return test.get("teacher").name.lower()
    

But as I did this, no param was passed to compare_function. So the "obj" in compare_func will be None.

Then I tried to changed to

return sorted(qs, key=compare_function(obj, cls_name), reverse=True)

However, the interpretor complained the obj can’t be found this time.

How can I do?

Thanks.:)

p.s. I’m seeking for a general solution. :’)

Asked By: Alston

||

Answers:

You can pass a lambda as the key that invokes compare_function with an extra argument:

key=lambda x: compare_function(x, cls_name)
Answered By: Unmitigated
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.