Skip to content

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

@glyph

Description

@glyph

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions