我有以下一段代码(展开以获得更清楚的解释),我希望它始终具有布尔变量类型.然而,mypy表示第二个和第三个类型并不总是bool
,而是list
、None
和bool
的并集.
a: list[str] | None = None
b: list[str] | None = None
def f(test: str) -> bool:
flag: bool = not a and not b
flag2: bool = a and test in a
flag3: bool = b and test not in b
return flag or flag2 or flag3
如果我将第二行更改为a is not None
(以及第三行),所指示的输入将变为正确.既然表达式总是条件式,那么类型不应该解析为布尔型吗?为什么is not None
是必要的?
以下是显示错误的操场链接:https://mypy-play.net/?mypy=latest&python=3.11&flags=verbose&gist=14167cfb7554c2c94c3bd65d2710d017