2

I get unexpected mypy errors when using builtin binary operations on variables of type TypeVar('T', bound=int|float).

Here is a minimal example:

import typing

T = typing.TypeVar('T', bound=typing.Union[int, float])

def less_than(x: T, y: T) -> bool:
    return x < y

mypy gives me the following error:

test.py:6: error: Unsupported operand types for < ("int" and "T")

Why do I get that error?

On a side note: mypy doesn't complain if I use T = typing.Union[int, float] or T = typing.TypeVar('T', int, float).

jfschaefer
  • 293
  • 1
  • 8
  • 1
    Possibly relevant: https://github.com/python/mypy/issues/12800. – chepner Jun 21 '22 at 12:58
  • Looking at https://github.com/python/typeshed/blob/master/stdlib/_operator.pyi, `__lt__` is typed using a union of protocols, which themselves are all typed with `Any`. My theory is that `Any` does *not* include `Union[int, float]`, only concrete types, and using `Union` as an upper bound on a type hint (rather than a type hint itself) prevents `mypy` from "realizing" `T` as a concrete type. – chepner Jun 21 '22 at 13:13
  • (All of which is to say, it *feels* like an upper bound of `Union` is too vague, but I can't really articulate why it should or should not work. I'm looking forward to a good answer for this question.) – chepner Jun 21 '22 at 13:14
  • 1
    also relevant https://stackoverflow.com/q/59933946/5986907 – joel Jun 21 '22 at 19:34

0 Answers0