Skip to content

Commit b58e8ee

Browse files
committed
Reject bound covariant type variable in List argument
1 parent c5814e5 commit b58e8ee

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

mypy/checker.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,11 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str])
947947
if ctx.line < 0:
948948
ctx = typ
949949
self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx)
950+
elif (is_named_instance(arg_type, 'builtins.list')
951+
and isinstance(self.iterable_item_type(arg_type), TypeVarType)):
952+
if(self.iterable_item_type(arg_type).variance == COVARIANT):
953+
message = "Cannot use a covariant type variable as a parameter"
954+
self.fail(message, arg_type)
950955
if typ.arg_kinds[i] == nodes.ARG_STAR:
951956
# builtins.tuple[T] is typing.Tuple[T, ...]
952957
arg_type = self.named_generic_type('builtins.tuple',

test-data/unit/check-functions.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2066,6 +2066,18 @@ class A(Generic[t]):
20662066
[out]
20672067
main:5: error: Cannot use a covariant type variable as a parameter
20682068

2069+
[case testRejectListCovariantArgument]
2070+
from typing import TypeVar, List, Generic
2071+
2072+
t = TypeVar('t', covariant=True)
2073+
class A(Generic[t]):
2074+
def foo(self, x: List[t]) -> None:
2075+
return None
2076+
[builtins fixtures/bool.pyi]
2077+
[builtins fixtures/list.pyi]
2078+
[out]
2079+
main:5: error: Cannot use a covariant type variable as a parameter
2080+
20692081
[case testRejectCovariantArgumentSplitLine]
20702082
from typing import TypeVar, Generic
20712083

0 commit comments

Comments
 (0)