abs(Union[int, Decimal]) is inferred as object
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 20.6k
- 派生
- 3.3k
- PR 合并指标
- PR 指标待抓取
描述
I'm afraid I'm not sure whether I'm reporting a bug or requesting a feature. I'm happy to leave that up for you all to triage. I'll start with what I'm seeing and what I'd like to see, and then get a little bit into the why.
Here's a minimal reproduction:
from decimal import Decimal
from typing import Union
def check(x: Decimal, y: Union[Decimal, int]) -> bool:
return x < -abs(y)
With Python 3.7.3 (from Debian buster) and mypy 0.770 (from PyPI), checking this code returns an error:
deccomp.py:6: error: Unsupported operand type for unary - ("object") [operator]
Found 1 error in 1 file (checked 1 source file)
The return type of abs is inferred as object, I think because that's the common supertype of int and Decimal. It would be nice if, one way or another, the return type of abs could be inferred as some higher numeric type.
The context here is I'm working on accounting software where I want to be careful to do decimal math throughout. In other words, I never want to deal with the decimal.FloatOperation signal. For functions that do basic arithmetic or comparisons across numbers, it's fine to accept arguments that are either int or Decimal, and it's convenient for callers if I can annotate that argument type rather than requiring them to convert their integer arguments to Decimal all the time.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 deccomp.py 中的最小复现开始,并使用 mypy 运行它,以确认 abs(y) 被推断为 object 并导致一元负号错误。调查 abs 针对 Union[Decimal, int] 的类型标注方式;完成标准是示例能够通过类型检查,不再出现 object 操作数错误,同时保留对 Decimal 安全的算术运算。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100