mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Lint against cases where user likely intended to use constrained type variables

Open hyperkai opened this issue 1 month ago • 2 comments

*Memo:

  • mypy test.py
  • mypy 1.18.2
  • Python 3.14.0
  • Windows 11

Instantiating the object of the class with the wrong syntax setting constraint types to the 2nd and 3rd arguments gets error properly as shown below:

                  # ↓↓↓↓↓↓↓↓↓↓ Wrong syntax
class MyCls[T: int, float, str]:
    num: T
    def __init__(self, x: T) -> None:
        self.num = x

# Instantiation
MyCls[int](100)
# Error

error: Type application has too few types

But only defining the class with the wrong syntax doesn't get the error as shown below so the error should occur:

                  # ↓↓↓↓↓↓↓↓↓↓ Wrong syntax
class MyCls[T: int, float, str]:
    num: T
    def __init__(self, x: T) -> None:
        self.num = x
# No error

hyperkai avatar Nov 28 '25 18:11 hyperkai

Hmm interesting report, thanks.

This is technically valid syntax: it defines three type variables, one called T with an upper bound of int, one called float, and one called str. I guess mypy could lint against this by either complaining about type variables whose names match builtins (not ideal, but a lot of constrained type variables are constrained to builtins) or potentially attempting to find unused type variables.

hauntsaninja avatar Nov 28 '25 20:11 hauntsaninja

Warning against unused type variables seems useful in general. In this example case, it's plausible that names like float and str will appear in the class body though.

A linter could also warn against typevars with names that don't start with an uppercase letter. It's not a hard rule, but it's a very strong convention in the ecosystem that typevars have uppercase names, usually ending in T. This rule would be more fit for a linter, though.

JelleZijlstra avatar Nov 29 '25 03:11 JelleZijlstra