abs(Union[int, Decimal]) is inferred as object
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der minimalen Reproduktion in deccomp.py und führe sie mit mypy aus, um zu bestätigen, dass abs(y) als object inferiert wird und den Unary-Minus-Fehler verursacht. Untersuche, wie abs für Union[Decimal, int] typisiert ist; abgeschlossen ist die Aufgabe, wenn das Beispiel ohne den Fehler mit dem object-Operand einen Type-Check besteht und dabei Decimal-sichere Arithmetik erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100