Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject bound covariant type variable in List argument #9269

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about Dict and (possibly) other types?

from typing import Dict, TypeVar

T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)

def cov(a: Dict[T_co, T_co]) -> Dict[T_co, T_co]:
    ...

def contra(a: Dict[T_contra, T_contra]) -> Dict[T_contra, T_contra]:
    ...

reveal_type(cov({'a': 1}))
reveal_type(contra({'a': 1}))

Outputs:

ex.py:12: error: Cannot infer type argument 1 of "cov"
ex.py:12: note: Revealed type is 'builtins.dict[Any, Any]'
ex.py:13: error: Cannot infer type argument 1 of "contra"
ex.py:13: note: Revealed type is 'builtins.dict[Any, Any]'

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