Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 912
Dušan Maďar Avatar asked Nov 01 '25 08:11

Dušan Maďar


1 Answers

The answer by @SisodiaMonu 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, 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:

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.

like image 77
STerliakov Avatar answered Nov 02 '25 23:11

STerliakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!