Skip to content

Commit

Permalink
Reject bound covariant type variable in List argument
Browse files Browse the repository at this point in the history
  • Loading branch information
LiuYuHui committed Aug 6, 2020
1 parent c5814e5 commit 85d5ba9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-functions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 85d5ba9

Please sign in to comment.