diff --git a/mypy/checker.py b/mypy/checker.py index 50fd6601dbe4..b343e644d590 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -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, ...] diff --git a/test-data/unit/check-classes.test b/test-data/unit/check-classes.test index 87e3342efa15..c277250f64f6 100644 --- a/test-data/unit/check-classes.test +++ b/test-data/unit/check-classes.test @@ -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