Skip to content

Commit d0b3fb3

Browse files
authored
Fix type variable with values as a supertype (#21431)
Fixes #21424 Unless I am missing something, this should be allowed.
1 parent 4e349a7 commit d0b3fb3

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

mypy/subtypes.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,8 @@ def _is_subtype(
312312
# ErasedType as we do for non-proper subtyping.
313313
return True
314314

315+
# Cases specific w.r.t. right type are easier to handle before entering the SubtypeVisitor.
316+
# Currently, these include Union types and TypeVarType with values.
315317
if isinstance(right, UnionType) and not isinstance(left, UnionType):
316318
# Normally, when 'left' is not itself a union, the only way
317319
# 'left' can be a subtype of the union 'right' is if it is a
@@ -360,6 +362,17 @@ def _is_subtype(
360362
elif is_subtype_of_item:
361363
return True
362364
# otherwise, fall through
365+
366+
if isinstance(right, TypeVarType) and right.values and not isinstance(left, TypeVarType):
367+
if proper_subtype:
368+
if all(
369+
is_proper_subtype(orig_left, v, subtype_context=subtype_context)
370+
for v in right.values
371+
):
372+
return True
373+
elif all(is_subtype(orig_left, v, subtype_context=subtype_context) for v in right.values):
374+
return True
375+
363376
return left.accept(SubtypeVisitor(orig_right, subtype_context, proper_subtype))
364377

365378

test-data/unit/check-typevar-values.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,3 +744,17 @@ def fn(w: W) -> W:
744744
reveal_type(w) # N: Revealed type is "builtins.int"
745745
return w
746746
[builtins fixtures/isinstance.pyi]
747+
748+
[case testTypeVarValuesSubtypeOfAll]
749+
from typing import TypeVar
750+
751+
class B: ...
752+
class C(B): ...
753+
754+
S = TypeVar("S", B, C)
755+
b = B()
756+
c = C()
757+
def g(x: S = c): # OK
758+
...
759+
def h(x: S = b): # E: Incompatible default for parameter "x" (default has type "B", parameter has type "S")
760+
...

0 commit comments

Comments
 (0)