mypy with dictionary’s get function

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

mypy with dictionary's get function

问题

我有一些类似这样的代码:

di: dict[str, float]

max_val = max(di, key=di.get)

在运行mypy时,它报错:

error: Argument "key" to "max" has incompatible type overloaded function; expected "Callable[[str], Union[SupportsDunderLT[Any], SupportsDunderGT[Any]]]"

我的猜测是这是因为di.get的返回类型通常是Union[float, None],但在这个特定实例中,它应该始终返回一个float,因为该函数只在di的键上调用。我发现的三种解决方法是定义一个自定义lambda函数,忽略di.get调用,或者使用cast如下:

get_lambda = lambda key: di[key]
max_val = max(di, key=get_lambda)

# ---------

max_val = max(
    di,
    key=di.get,  # type: ignore [arg-type]
)

# ---------

from typing import cast, Callable

max_val = max(di, key=cast(Callable[[str], float], di.get))

是否有一种更合适/标准的方法来告诉mypy get方法不会返回None

英文:

I have some code that looks like this:

di: dict[str, float]

max_val = max(di, key=di.get)

When running mypy on it, it complains

error: Argument "key" to "max" has incompatible type overloaded function; expected "Callable[[str], Union[SupportsDunderLT[Any], SupportsDunderGT[Any]]]"

My guess is that this is because the return type of di.get is Union[float, None] in general, but in this specific instance, it should always return a float since the function is only being called on keys from di. The three workarounds I've discovered are to define a custom lambda function, ignore the di.get call, or cast it as follows.

get_lambda = lambda key: di[key]
max_val = max(di, key=get_lambda)

# ---------

max_val = max(
    di,
    key=di.get,  # type: ignore [arg-type]
)

# ---------

from typing import cast, Callable

max_val = max(di, key=cast(Callable[[str], float], di.get))

Is there a more proper/standard way of letting mypy know that the get method will not be returning None?

答案1

得分: 2

双下划线(__)成员函数 __getitem__dict 对象中是你想要的:

max(di, key=di.__getitem__) 

不会引发 mypy 的任何投诉。你的 lambda 函数之所以有效,是因为它精确地模拟了 __getitem__ 的意图,即实现了 self[key] 的评估,正如文档中所解释的。

英文:

The dunder (double underscore) member function __getitem__ of a dict object is what you want here:

max(di, key=di.__getitem__) 

raises no complains from mypy. The reason your lambda works is because it precisely emulates the intent of __getitem__, which is to implement evaluation of self[key], as explained in the documentation.

huangapple
  • 本文由 发表于 2023年2月7日 03:41:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定