0

Given the following Python file:

class SomeValue:
    def __init__(self, value: int):
        self.value = value

some_values = sorted([SomeValue(3), SomeValue(4)], lambda v: v.value)

When running mypy on this, I get

demo.py:5: error: No overload variant of "sorted" matches argument types "List[SomeValue]", "Callable[[Any], Any]"
demo.py:5: note: Possible overload variants:
demo.py:5: note:     def [SupportsLessThanT <: SupportsLessThan] sorted(Iterable[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> List[SupportsLessThanT]
demo.py:5: note:     def [_T] sorted(Iterable[_T], *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> List[_T]
Found 1 error in 1 file (checked 1 source file)

I don't really understand what makes mypy unhappy.

jan
  • 1,408
  • 13
  • 19

1 Answers1

1

Try:

some_values = sorted([SomeValue(3), SomeValue(4)], key=lambda v: v.value)
Bibhav
  • 1,579
  • 1
  • 5
  • 18
  • Thanks, that works! My autocompletion indicated, that `key` is simply the second parameter, not sure why that doesn't work. – jan Mar 14 '22 at 11:54
  • `key` is a **keyword argument** so `key=func` is necessary. – Bibhav Mar 14 '22 at 11:58