This rule raises an issue when a TypeVar is declared with both covariant=True and contravariant=True.

Why is this an issue?

A TypeVar in Python represents a type variable used in generic programming. It can have one of three variance modes:

These variance modes are mutually exclusive. A type variable cannot be both covariant and contravariant simultaneously because these represent opposite relationships in the type hierarchy. Python’s typing module will raise a ValueError at runtime when it encounters such a declaration.

What is the potential impact?

How to fix it

Choose the appropriate variance mode for your type variable:

Code examples

Noncompliant code example

from typing import TypeVar

# Invalid: cannot be both covariant and contravariant
T = TypeVar('T', covariant=True, contravariant=True)  # Noncompliant

Compliant solution

from typing import TypeVar

# Valid: covariant type variable
T_co = TypeVar('T_co', covariant=True)

Resources

Documentation