Home > Enterprise >  Python: Typing a lambda function for use with sorted
Python: Typing a lambda function for use with sorted

Time:03-15

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.

CodePudding user response:

Try:

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