Skip to content

Enable negative narrowing of Union TypeVar upper bounds #17850

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1930,6 +1930,8 @@ def restrict_subtype_away(t: Type, s: Type) -> Type:
if (isinstance(get_proper_type(item), AnyType) or not covers_at_runtime(item, s))
]
return UnionType.make_union(new_items)
elif isinstance(p_t, TypeVarType):
return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s))
elif covers_at_runtime(t, s):
return UninhabitedType()
else:
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/check-isinstance.test
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,30 @@ def f(x: T) -> None:
reveal_type(x) # N: Revealed type is "T`-1"
[builtins fixtures/isinstance.pyi]

[case testIsinstanceAndNegativeNarrowTypeVariableWithUnionBound]
from typing import Union, TypeVar

class A:
a: int
class B:
b: int

T = TypeVar("T", bound=Union[A, B])

def f(x: T) -> T:
if isinstance(x, A):
reveal_type(x) # N: Revealed type is "__main__.A"
x.a
x.b # E: "A" has no attribute "b"
else:
reveal_type(x) # N: Revealed type is "T`-1"
x.a # E: "T" has no attribute "a"
x.b
x.a # E: Item "B" of the upper bound "Union[A, B]" of type variable "T" has no attribute "a"
x.b # E: Item "A" of the upper bound "Union[A, B]" of type variable "T" has no attribute "b"
return x
[builtins fixtures/isinstance.pyi]

[case testIsinstanceAndTypeType]
from typing import Type
def f(x: Type[int]) -> None:
Expand Down
Loading