Reep
Reep

Reputation: 566

Why is it OK to pass a class to the key attribute of Python's sorted() function?

I came across code something like this and am trying to understand how it works. From the python documentation for sorted() the key parameter takes a function which takes a single argument and then returns a key to be used in the comparison. This code is assigning key a class. How is this ok? And how does __lt__ get x and y passed to it?

class K(str):
    def __lt__(x, y):
        return x > y
input = [3, 30, 7]
sorted(input, key=K)

Output: [7, 30, 3]

Upvotes: 2

Views: 505

Answers (1)

shermr
shermr

Reputation: 111

python uses duck typing, so it doesn't check if the key is a function, it just calls it. the key argument is used in sorted to determine what to compare. In this case, instead of comparing [3, 30, 7] it's comparing [K(3), K(30), K(7)]. That's also why there's a __lt__ method implemented, for the less than comparison

Upvotes: 3

Related Questions