diff --git a/mypy/checker.py b/mypy/checker.py index 75739fe87a00..79e7e87accd5 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -947,6 +947,14 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str]) if ctx.line < 0: ctx = typ self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx) + elif is_named_instance(arg_type, 'builtins.list'): + arg_typ = get_proper_type(arg_type) + if isinstance(arg_typ, Instance): + item_type = self.iterable_item_type(arg_typ) + if (isinstance(item_type, TypeVarType) + and item_type.variance == COVARIANT): + message = "Cannot use a covariant type variable as a parameter" + self.fail(message, arg_type) if typ.arg_kinds[i] == nodes.ARG_STAR: # builtins.tuple[T] is typing.Tuple[T, ...] arg_type = self.named_generic_type('builtins.tuple', diff --git a/test-data/unit/check-functions.test b/test-data/unit/check-functions.test index c0092f1057c2..3326948325d6 100644 --- a/test-data/unit/check-functions.test +++ b/test-data/unit/check-functions.test @@ -2066,6 +2066,18 @@ class A(Generic[t]): [out] main:5: error: Cannot use a covariant type variable as a parameter +[case testRejectListCovariantArgument] +from typing import TypeVar, List, Generic + +t = TypeVar('t', covariant=True) +class A(Generic[t]): + def foo(self, x: List[t]) -> None: + return None +[builtins fixtures/bool.pyi] +[builtins fixtures/list.pyi] +[out] +main:5: error: Cannot use a covariant type variable as a parameter + [case testRejectCovariantArgumentSplitLine] from typing import TypeVar, Generic