Python list.sort(key=lambda x: …) type hints

huangapple go评论121阅读模式
英文:

Python list.sort(key=lambda x: ...) type hints

问题

我正在根据以下方式的键对字典列表进行排序

  1. my_function() -> list[dict]:
  2. data: list[dict] = []
  3. # 填充数据...
  4. if condition:
  5. data.sort(key=lambda x: x["position"])
  6. 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

  1. my_function() -> list[dict]:
  2. data: list[dict] = []
  3. # Populate data ...
  4. if condition:
  5. data.sort(key=lambda x: x["position"])
  6. 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

  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`,这个问题就不会出现:
  2. ```python
  3. from typing import TypedDict
  4. class MyItem(TypedDict):
  5. position: int
  6. key: str
  7. condition = True
  8. def my_function() -> list[MyItem]:
  9. data: list[MyItem] = []
  10. # Populate data ...
  11. if condition:
  12. data.sort(key=lambda x: x["position"])
  13. return data

你可以在playground中尝试这个解决方案。

  1. <details>
  2. <summary>英文:</summary>
  3. 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&#39;s `{&#39;position&#39;: 1, &#39;key&#39;: &#39;foo&#39;}`, then the type would&#39;ve been `dict[str, int | str]`, and `mypy` will point out invalid comparison (`int | str` is not comparable). With `TypedDict`, this problem won&#39;t arise:
  4. ```python
  5. from typing import TypedDict
  6. class MyItem(TypedDict):
  7. position: int
  8. key: str
  9. condition = True
  10. def my_function() -&gt; list[MyItem]:
  11. data: list[MyItem] = []
  12. # Populate data ...
  13. if condition:
  14. data.sort(key=lambda x: x[&quot;position&quot;])
  15. return data

You can try this solution in playground.

huangapple
  • 本文由 发表于 2023年2月16日 19:26:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定