Python:键入用于排序的 lambda 函数
Python: Typing a lambda function for use with sorted
给定以下 Python 文件:
class SomeValue:
def __init__(self, value: int):
self.value = value
some_values = sorted([SomeValue(3), SomeValue(4)], lambda v: v.value)
当运行mypy
在这上面,我得到
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)
我真的不明白是什么让 mypy
不开心。
尝试:
some_values = sorted([SomeValue(3), SomeValue(4)], key=lambda v: v.value)
给定以下 Python 文件:
class SomeValue:
def __init__(self, value: int):
self.value = value
some_values = sorted([SomeValue(3), SomeValue(4)], lambda v: v.value)
当运行mypy
在这上面,我得到
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)
我真的不明白是什么让 mypy
不开心。
尝试:
some_values = sorted([SomeValue(3), SomeValue(4)], key=lambda v: v.value)