英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论