Search code examples
pythonlambdatypestype-hintingmypy

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)


Solution

  • 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.