Ignore incompatible type error when variable is checked in if statement
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
I'm using mypy for type checking in my Python projects and I've come across a situation where I believe mypy could be improved.
Consider the following code:
def foo1(a: str): ...
def foo2(a: str | None, b: str | None):
if not a and not b:
return None
if not a:
return foo1(b)
return None
In this case, mypy raises an error:
Argument 1 to "foo1" has incompatible type "str | None"; expected "str" [arg-type].
However, the function foo1 is only called when b
is not None, so in practice, there is no type error.
The logic of the function ensures that b cannot be None when foo1(b) is called.
This is because in the first if statement, we check if both a and b are None.
If they are not, we proceed to the next if statement where we check if a is None.
If a is None, then b must not be None because of the previous check.
Therefore, foo1(b) is only called when b is not None.
Versions
Python: 3.10.10
MyPy: 1.7.1
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先在提供的 Python 复现程序上运行 mypy,并追踪两个 if 语句如何影响类型收窄。找出相关的类型检查测试或入口点,然后为此控制流添加一个回归用例。当 mypy 接受 foo1(b) 且不产生 arg-type 错误,同时保留现有检查时,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100