Skip to content

Commit

Permalink
Fix narrowing union types that include Self with isinstance (#14923)
Browse files Browse the repository at this point in the history
Fix narrowing union types that include Self with isinstance (Fixes #14912).

The special case of bound type variables was not handled in function `covers_at_runtime` of module `subtypes`.  So I added it and defined the test case `testNarrowSelfType`.
  • Loading branch information
tyralla authored Mar 25, 2023
1 parent 46ab0f8 commit c5ddc36
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
3 changes: 3 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1802,6 +1802,9 @@ def covers_at_runtime(item: Type, supertype: Type) -> bool:
# Special case useful for selecting TypedDicts from unions using isinstance(x, dict).
if supertype.type.fullname == "builtins.dict":
return True
elif isinstance(item, TypeVarType):
if is_proper_subtype(item.upper_bound, supertype, ignore_promotions=True):
return True
elif isinstance(item, Instance) and supertype.type.fullname == "builtins.int":
# "int" covers all native int types
if item.type.fullname in MYPYC_NATIVE_INT_NAMES:
Expand Down
18 changes: 18 additions & 0 deletions test-data/unit/check-selftype.test
Original file line number Diff line number Diff line change
Expand Up @@ -1829,3 +1829,21 @@ class C(Generic[T]):
reveal_type(self.val) # N: Revealed type is "__main__.A" \
# N: Revealed type is "__main__.B"
self.val = x

[case testNarrowSelfType]
from typing import Self, Union

class A: ...
class B:
def f1(self, v: Union[Self, A]) -> A:
if isinstance(v, B):
return A()
else:
return v
def f2(self, v: Union[Self, A]) -> A:
if isinstance(v, B):
return A()
else:
return B() # E: Incompatible return value type (got "B", expected "A")

[builtins fixtures/isinstancelist.pyi]

0 comments on commit c5ddc36

Please sign in to comment.