Skip to content

Commit 54a80bb

Browse files
committed
Address offline feedback
1 parent 21a2153 commit 54a80bb

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

mypy/join.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,9 @@ def visit_erased_type(self, t: ErasedType) -> ProperType:
298298

299299
def visit_type_var(self, t: TypeVarType) -> ProperType:
300300
if isinstance(self.s, TypeVarType) and self.s.id == t.id:
301-
return self.s
301+
if self.s.upper_bound == t.upper_bound:
302+
return self.s
303+
return self.s.copy_modified(upper_bound=join_types(self.s.upper_bound, t.upper_bound))
302304
else:
303305
return self.default(self.s)
304306

mypy/meet.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,9 @@ def visit_erased_type(self, t: ErasedType) -> ProperType:
786786

787787
def visit_type_var(self, t: TypeVarType) -> ProperType:
788788
if isinstance(self.s, TypeVarType) and self.s.id == t.id:
789-
return self.s
789+
if self.s.upper_bound == t.upper_bound:
790+
return self.s
791+
return self.s.copy_modified(upper_bound=self.meet(self.s.upper_bound, t.upper_bound))
790792
else:
791793
return self.default(self.s)
792794

mypyc/test-data/run-classes.test

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2983,3 +2983,31 @@ class B(native.A):
29832983

29842984
b: B = B.make()
29852985
assert(B.count == 2)
2986+
2987+
[case testTypeVarNarrowing]
2988+
from typing import TypeVar
2989+
2990+
class B:
2991+
def __init__(self, x: int) -> None:
2992+
self.x = x
2993+
class C(B):
2994+
def __init__(self, x: int, y: str) -> None:
2995+
self.x = x
2996+
self.y = y
2997+
2998+
T = TypeVar("T", bound=B)
2999+
def f(x: T) -> T:
3000+
if isinstance(x, C):
3001+
print("C", x.y)
3002+
return x
3003+
print("B", x.x)
3004+
return x
3005+
3006+
[file driver.py]
3007+
from native import f, B, C
3008+
3009+
f(B(1))
3010+
f(C(1, "yes"))
3011+
[out]
3012+
B 1
3013+
C yes

0 commit comments

Comments
 (0)