Skip to content

Commit 95e58fa

Browse files
ilevkivskyiJukkaL
authored andcommitted
Allow covariant args in constructor (#2888)
Fixes #2850 It looks like we could make a simple exclusion for __init__ and __new__.
1 parent 9a578fa commit 95e58fa

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

mypy/checker.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,10 @@ def is_implicit_any(t: Type) -> bool:
582582
elif isinstance(arg_type, TypeVarType):
583583
# Refuse covariant parameter type variables
584584
# TODO: check recursively for inner type variables
585-
if arg_type.variance == COVARIANT:
585+
if (
586+
arg_type.variance == COVARIANT and
587+
defn.name() not in ('__init__', '__new__')
588+
):
586589
self.fail(messages.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, arg_type)
587590
if typ.arg_kinds[i] == nodes.ARG_STAR:
588591
# builtins.tuple[T] is typing.Tuple[T, ...]

test-data/unit/check-classes.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1942,6 +1942,21 @@ def new_pro_user(user_class: Type[ProUser]):
19421942
new_user(user_class)
19431943
[out]
19441944

1945+
[case testAllowCovariantArgsInConstructor]
1946+
from typing import Generic, TypeVar
1947+
1948+
T_co = TypeVar('T_co', covariant=True)
1949+
1950+
class C(Generic[T_co]):
1951+
def __init__(self, x: T_co) -> None: # This should be allowed
1952+
self.x = x
1953+
def meth(self) -> None:
1954+
reveal_type(self.x) # E: Revealed type is 'T_co`1'
1955+
1956+
reveal_type(C(1).x) # E: Revealed type is 'builtins.int*'
1957+
[builtins fixtures/property.pyi]
1958+
[out]
1959+
19451960
[case testTypeUsingTypeCErrorCovariance]
19461961
from typing import Type, TypeVar
19471962
class User: pass

0 commit comments

Comments
 (0)