Type checking with sorted `key=`

I’m kind of new here, so I don’t know if this is the appropriate place to ask such questions. If I’m asking in the wrong place, please point me elsewhere.

Anyway, some code demonstrating the issue.

numbers: dict[str,float] = {
    "one": 1.,
    "pi": 3.14,
    "e": 2.71,
}

sorted_keys: list[str] = sorted(numbers, key = lambda name: numbers[name])

same_again: list[str] = sorted(numbers, key = numbers.get)

When I use pyright or mypy, I get an error with the key = numbers.get) case, while the form using the lambda passes.

From what I gather from the very convoluted type checking errors is that .get is a callable that can return None or that the type checkers don’t know that it will never return None in this setup. The type checkers do know that the function defined with the lambda will only ever return float, so all is cool.

So my questions are

  1. Should I just use this kind of lambda construction in these cases?
  2. Is there a performance hit in using lambda construction versus using my_dict.get ?

The lambda is likely to be a little slower. What’s even better to use is numbers.__getitem__, which will do the same thing as the lambda.

1 Like

Thank you, @TeamSpen210. I wasn’t aware of __getitem__. I’ve tested, it works, and the type checkers are happy with it.