英文:
Python list.sort(key=lambda x: ...) type hints
问题
我正在根据以下方式的键对字典列表进行排序
my_function() -> list[dict]:
data: list[dict] = []
# 填充数据...
if condition:
data.sort(key=lambda x: x["position"])
return data
然而,mypy 报错 Returning Any from function declared to return "Union[SupportsDunderLT[Any], SupportsDunderGT[Any]]"
. 是否可以更新上面的片段,以便 mypy 不会引发 no-any-return
错误?
编辑
版本:Python 3.10.9 和 mypy 1.0.0 (已编译:是)
英文:
I am sorting a list of dicts based on a key like below
my_function() -> list[dict]:
data: list[dict] = []
# Populate data ...
if condition:
data.sort(key=lambda x: x["position"])
return data
However mypy complains about Returning Any from function declared to return "Union[SupportsDunderLT[Any], SupportsDunderGT[Any]]"
. Is it possible to update the above snippet so that mypy doesn't raise a no-any-return
error?
EDIT
Versions: Python 3.10.9 and mypy 1.0.0 (compiled: yes)
答案1
得分: 1
答案[@SisodiaMonu](https://stackoverflow.com/a/75471999/14401160)应该有效。然而,看起来你的例子更像是使用字典作为JS对象,所以所有键都有语义含义。对于这种情况,有一种[`typing.TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict),允许你用类型注解所有字典键。这很重要,如果你的字典可能包含其他类型的对象:如果是`{'position': 1, 'key': 'foo'}`,那么类型将是`dict[str, int | str]`,而`mypy`将指出无效的比较(`int | str`是不可比较的)。使用`TypedDict`,这个问题就不会出现:
```python
from typing import TypedDict
class MyItem(TypedDict):
position: int
key: str
condition = True
def my_function() -> list[MyItem]:
data: list[MyItem] = []
# Populate data ...
if condition:
data.sort(key=lambda x: x["position"])
return data
你可以在playground中尝试这个解决方案。
<details>
<summary>英文:</summary>
The answer by [@SisodiaMonu](https://stackoverflow.com/a/75471999/14401160) should work. However, seems that your example uses dict more like a JS object, so all keys have semantic meaning. For such cases there is a [`typing.TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict), which allows you to annotate all dict keys with types. This is important, if your dict can contain some objects of other types: if it's `{'position': 1, 'key': 'foo'}`, then the type would've been `dict[str, int | str]`, and `mypy` will point out invalid comparison (`int | str` is not comparable). With `TypedDict`, this problem won't arise:
```python
from typing import TypedDict
class MyItem(TypedDict):
position: int
key: str
condition = True
def my_function() -> list[MyItem]:
data: list[MyItem] = []
# Populate data ...
if condition:
data.sort(key=lambda x: x["position"])
return data
You can try this solution in playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论