Lint against cases where user likely intended to use constrained type variables
*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
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.
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.