mypy“ Optional [Dict [Any,Any]]]”在标准过滤器,地图内不可索引

问题描述 投票:0回答:1

给出以下代码:

from typing import Optional, Dict

def foo(b: bool) -> Optional[Dict]:
    return {} if b else None


def bar() -> None:
    d = foo(False)

    if not d:
        return

    filter(lambda x: d['k'], [])

mypy 0.770失败,并在bar的最后一行上出现以下错误:Value of type "Optional[Dict[Any, Any]]" is not indexablemap也一样。更改行以使用列表推导或pydash中的filter_map_可解决错误。

为什么即使有类型保护,mypy为什么在使用标准filter时也会抛出错误?

python python-3.x typing mypy
1个回答
0
投票

我不确定为什么会这样,但是ifassert之后发生的类型缩小不会传播到内部范围,即使从逻辑上讲应该如此。一种简单的解决方法是将一个较窄的类型绑定到新变量,例如:

def bar() -> None:
    d = foo(False)

    if not d:
        return
    d_exists = d

    filter(lambda x: d_exists['k'], [])
© www.soinside.com 2019 - 2024. All rights reserved.