diff --git a/mypy/semanal.py b/mypy/semanal.py index bad2dfbefae0..64e7524715f4 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -295,7 +295,7 @@ type_vars_as_args, ) from mypy.types_utils import is_invalid_recursive_alias, store_argument_type -from mypy.typevars import fill_typevars +from mypy.typevars import fill_typevars, has_no_typevars from mypy.util import correct_relative_import, is_dunder, module_prefix, unmangle, unnamed_function from mypy.visitor import NodeVisitor @@ -5044,7 +5044,15 @@ def analyze_value_types(self, items: list[Expression]) -> list[Type]: # soon, even if some value is not ready yet, see process_typevar_parameters() # for an example. analyzed = PlaceholderType(None, [], node.line) - result.append(analyzed) + + # has_no_typevars does not work with PlaceholderType. + if not has_placeholder(analyzed) and not has_no_typevars(analyzed): + self.fail( + "TypeVar constraint type cannot be parametrized by type variables", node + ) + result.append(AnyType(TypeOfAny.from_error)) + else: + result.append(analyzed) except TypeTranslationError: self.fail("Type expected", node) result.append(AnyType(TypeOfAny.from_error)) diff --git a/test-data/unit/semanal-errors.test b/test-data/unit/semanal-errors.test index 33c8f9b80aa0..d0c2b924de62 100644 --- a/test-data/unit/semanal-errors.test +++ b/test-data/unit/semanal-errors.test @@ -1060,6 +1060,19 @@ S = TypeVar('S', covariant=True, contravariant=True) \ # E: TypeVar cannot be both covariant and contravariant [builtins fixtures/bool.pyi] +[case testInvalidTypevarArgumentsGenericConstraint] +from typing import Generic, List, TypeVar +from typing_extensions import Self + +T = TypeVar("T") + +def f(x: T) -> None: + Bad = TypeVar("Bad", int, List[T]) # E: TypeVar constraint type cannot be parametrized by type variables +class C(Generic[T]): + Bad = TypeVar("Bad", int, List[T]) # E: TypeVar constraint type cannot be parametrized by type variables +class D: + Bad = TypeVar("Bad", int, List[Self]) # E: TypeVar constraint type cannot be parametrized by type variables + [case testInvalidTypevarValues] from typing import TypeVar b = TypeVar('b', *[int]) # E: Unexpected argument to "TypeVar()"