给出以下代码:
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 indexable
。 map
也一样。更改行以使用列表推导或pydash中的filter_
或map_
可解决错误。
为什么即使有类型保护,mypy为什么在使用标准filter
时也会抛出错误?
我不确定为什么会这样,但是if
或assert
之后发生的类型缩小不会传播到内部范围,即使从逻辑上讲应该如此。一种简单的解决方法是将一个较窄的类型绑定到新变量,例如:
def bar() -> None:
d = foo(False)
if not d:
return
d_exists = d
filter(lambda x: d_exists['k'], [])