python / python/mypy

it's not possible to define an 'add' that works with more than one kind of number when using number types directly

Open
#12,899 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I can't figure out how to write generic numeric code.

This is already covered to some extent by #3186, but that's about a higher-level numeric tower issue, rather than the very practical issue of code that can just work with int or float but has to keep the number type straight.

To Reproduce

from typing import TypeVar

Num = TypeVar("Num", bound=int | float)


def add(a: Num, b: Num) -> Num:
    return a + b

I actually want | Decimal | Fraction in there, but that makes the problem worse.

The same issue seems to occur with Generics.

Expected Behavior

No errors.

Actual Behavior

add.py:7: error: Incompatible return value type (got "float", expected "Num")
add.py:7: error: Unsupported operand types for + (likely involving Union)
Found 2 errors in 1 file (checked 1 source file)

I understand how this would not work if I were using division, or if there were some other variance on Num but is there really some way to add an int to an int and get a float?

Your Environment

  • Mypy version used: mypy 0.960 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.10.4 from python.org
  • Operating system and version:
ProductName:	macOS
ProductVersion:	12.4
BuildVersion:	21F79

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 by reproducing the diagnostic from add.py with the reported mypy version and review the related discussion in issue #3186. Investigate how bounded TypeVars, numeric unions, and Generic operands are analyzed; done means a supported generic numeric addition pattern type-checks without the reported errors and has regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.