python / python/mypy

abs(Union[int, Decimal]) is inferred as object

Open
#8,601 8 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-join-v-union topic-protocols
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal reproduction in deccomp.py and run it with mypy to confirm that abs(y) is inferred as object and causes the unary-minus error. Investigate how abs is typed for Union[Decimal, int]; done means the example type-checks without the object operand error while preserving Decimal-safe arithmetic.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.