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
- Should I just use this kind of
lambda
construction in these cases? - Is there a performance hit in using
lambda
construction versus usingmy_dict.get
?