Mypy doesn't seem to use types from @overload-ed __sub__
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
Bug Report
The __sub__ method on the Arrow class from the arrow package has several @overloads:
@overload
def __sub__(self, other: Union[timedelta, relativedelta]) -> "Arrow":
pass # pragma: no cover
@overload
def __sub__(self, other: Union[dt_datetime, "Arrow"]) -> timedelta:
pass # pragma: no cover
def __sub__(self, other: Any) -> Union[timedelta, "Arrow"]:
if isinstance(other, (timedelta, relativedelta)):
return self.fromdatetime(self._datetime - other, self._datetime.tzinfo)
elif isinstance(other, dt_datetime):
return self._datetime - other
elif isinstance(other, Arrow):
return self._datetime - other._datetime
return NotImplemented
In particular, one Arrow object minus another Arrow object will always yield a timedelta. However, it seems mypy does not see this, and mistakes the type for Arrow.
To Reproduce
I discovered the issue when finding the time diff between two arrow timestamps:
import arrow
a1 = arrow.get()
a2 = arrow.get()
diff = a2 - a1
print(diff.total_seconds())
Which, when run with mypy yields:
$ mypy test.py
test.py:6: error: "int" not callable
Found 1 error in 1 file (checked 1 source file)
Setting the type explicitly reviles that mypy thinks the type is Arrow, and not timedelta:
from datetime import timedelta
import arrow
a1 = arrow.get()
a2 = arrow.get()
diff: timedelta = a2 - a1
print(diff.total_seconds())
Running mypy:
$ mypy test.py
test.py:7: error: Incompatible types in assignment (expression has type "Arrow", variable has type "timedelta")
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
The second @overload on Arrow's __sub__ method specifies that the diff of two Arrow objects is a timedelta. There should be no type error assigning that to a timedelta variable.
Actual Behavior
Mypy mistakenly thinks the diff is Arrow, which creates a false positive.
Your Environment
- Mypy version used: 0.910
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.9.6
- Operating system and version: Mac OS 11.6 (Big Sur)
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先,使用 Python 代码片段和所述的 mypy 0.910 环境重现报告中的推断错误。阅读 arrow/arrow.py 中的重载声明,然后跟踪 mypy 对重载 sub 调用的处理;当 Arrow 减去 Arrow 被推断为 timedelta,且所示赋值和 total_seconds() 调用通过类型检查时,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- tooling
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100