Skip to content

Warn when PEP695 type param clashes with a TypeVar name #18499

Open
@leamingrad

Description

@leamingrad

Bug Report

When defining a generic class with a type variable bounded to number classes, arithmetic operations are not available in class methods.

To Reproduce

Playground link: https://mypy-play.net/?mypy=master&python=3.12&gist=97147ba435ef98e5566e5c6a01424f92

Sample program

from typing import TypeVar
from decimal import Decimal

TAmount = TypeVar("TAmount", int, Decimal)

class Box[TAmount]:
    def __init__(self, amount: TAmount) -> None:
        self.amount = amount
    
    def box_method_with_arithmetic(self, other: Box[TAmount]) -> None:
        add = self.amount + other.amount
        sub = self.amount - other.amount
        mul = self.amount * other.amount
        div = self.amount / other.amount
        floordiv = self.amount // other.amount
        pow = self.amount ** other.amount

def value_function_with_arithmetic(left: TAmount, right: TAmount) -> None:
    add = left + right
    sub = left - right
    mul = left * right
    div = left / right
    floordiv = left // right
    pow = left ** right

def box_function_with_arithmetic(left: Box[TAmount], right: Box[TAmount]) -> None:
    add = left.amount + right.amount
    sub = left.amount - right.amount
    mul = left.amount * right.amount
    div = left.amount / right.amount
    floordiv = left.amount // right.amount
    pow = left.amount ** right.amount

Expected Behavior

The program should typecheck successfully.

Actual Behavior

main.py:11: error: Unsupported left operand type for + ("TAmount")  [operator]
main.py:12: error: Unsupported left operand type for - ("TAmount")  [operator]
main.py:13: error: Unsupported left operand type for * ("TAmount")  [operator]
main.py:14: error: Unsupported left operand type for / ("TAmount")  [operator]
main.py:15: error: Unsupported left operand type for // ("TAmount")  [operator]
main.py:16: error: Unsupported left operand type for ** ("TAmount")  [operator]
Found 6 errors in 1 file (checked 1 source file)

This seems to only be a problem in methods on the generic class. The functions which operate on values and class instances typecheck cleanly.

Note that the TypeVar is defined as being exactly int or Decimal as per #12899 (comment).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions