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

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

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&#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:


```python
from typing import TypedDict


class MyItem(TypedDict):
    position: int
    key: str


condition = True

def my_function() -&gt; list[MyItem]:
    data: list[MyItem] = []

    # Populate data ...

    if condition:
        data.sort(key=lambda x: x[&quot;position&quot;])

    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:

确定