This rule raises an issue when a TypeVar, ParamSpec, or NewType is assigned to a variable whose name does not match the string name passed to its constructor.

Why is this an issue?

In Python’s typing system, TypeVar, ParamSpec, and NewType are special constructs used to define generic types and type aliases. When creating these objects, you provide a string name as the first argument to the constructor. The convention is that this string name should match the variable name to which the type is assigned.

When the names do not match, type checkers and runtime error messages use the string name from the constructor, which can make error messages confusing. IDEs and other development tools may also rely on this naming convention to provide accurate type information.

What is the potential impact?

Mismatched names create confusion for developers reading the code and make error messages harder to understand. This can slow down debugging and make code reviews more difficult, reducing overall development efficiency.

In larger codebases with multiple type variables, mismatched names can lead to mistakes when refactoring or extending generic classes and functions.

How to fix it

Ensure the string name passed to the constructor matches the variable name it is assigned to.

Code examples

Noncompliant code example

from typing import TypeVar, ParamSpec, NewType

MyType = TypeVar("T")  # Noncompliant: variable is "MyType" but string is "T"
MyParams = ParamSpec("P")  # Noncompliant: variable is "MyParams" but string is "P"
MyInt = NewType("Integer", int)  # Noncompliant: variable is "MyInt" but string is "Integer"

Compliant solution

from typing import TypeVar, ParamSpec, NewType

MyType = TypeVar("MyType")  # Compliant: names match
MyParams = ParamSpec("MyParams")  # Compliant: names match
MyInt = NewType("MyInt", int)  # Compliant: names match

Resources

Documentation