Skip to content

Allow covariant args in constructor #2888

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

Merged
merged 3 commits into from
Feb 21, 2017
Merged
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
5 changes: 4 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,10 @@ def is_implicit_any(t: Type) -> bool:
elif isinstance(arg_type, TypeVarType):
# Refuse covariant parameter type variables
# TODO: check recursively for inner type variables
if arg_type.variance == COVARIANT:
if (
arg_type.variance == COVARIANT and
defn.name() not in ('__init__', '__new__')
):
self.fail(messages.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, arg_type)
if typ.arg_kinds[i] == nodes.ARG_STAR:
# builtins.tuple[T] is typing.Tuple[T, ...]
Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -1942,6 +1942,21 @@ def new_pro_user(user_class: Type[ProUser]):
new_user(user_class)
[out]

[case testAllowCovariantArgsInConstructor]
from typing import Generic, TypeVar

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

class C(Generic[T_co]):
def __init__(self, x: T_co) -> None: # This should be allowed
self.x = x
def meth(self) -> None:
reveal_type(self.x) # E: Revealed type is 'T_co`1'

reveal_type(C(1).x) # E: Revealed type is 'builtins.int*'
[builtins fixtures/property.pyi]
[out]

[case testTypeUsingTypeCErrorCovariance]
from typing import Type, TypeVar
class User: pass
Expand Down