rkr*_*r87 0 python mypy typeddict
我创建了下面的 TypedDict 类;
class Appinfo(TypedDict):
appid: int
extended: dict[str, Any]
config: dict[str, Any]
depots: dict[str, Any]
ufs: dict[str, Any]
class SteamAppInfo(TypedDict):
appid: int
data: dict[str, Appinfo]
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我将此类的变量传递给需要字典的函数;
def dict_get_key_list(data: dict[str, Any], key_list: list[str]) -> Any:
"""returns a dict value or None based on list of nested dict keys provided"""
try:
return reduce(operator.getitem, key_list, data)
except KeyError:
return None
Run Code Online (Sandbox Code Playgroud)
代码本身运行良好,就所有意图和目的而言,SteamAppInfo 是一本字典。但是,MyPy 给我以下错误;
error: Argument 1 to "dict_get_key_list" of "Utils" has incompatible type "SteamAppInfo"; expected "Dict[str, Any]"
Run Code Online (Sandbox Code Playgroud)
如何让 MyPy 识别出传递的是字典,而不必列出我创建的所有 TypedDict 作为可能的变量类型或将变量类型设置为 Any?
| 归档时间: |
|
| 查看次数: |
1596 次 |
| 最近记录: |