Skip to content

Commit 85d5ba9

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

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

mypy/checker.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,14 @@ 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+
arg_typ = get_proper_type(arg_type)
952+
if isinstance(arg_typ, Instance):
953+
item_type = self.iterable_item_type(arg_typ)
954+
if (isinstance(item_type, TypeVarType)
955+
and item_type.variance == COVARIANT):
956+
message = "Cannot use a covariant type variable as a parameter"
957+
self.fail(message, arg_type)
950958
if typ.arg_kinds[i] == nodes.ARG_STAR:
951959
# builtins.tuple[T] is typing.Tuple[T, ...]
952960
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)