Skip to content

Commit a95bb8e

Browse files
committed
Fix edge case
1 parent 6e99af4 commit a95bb8e

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

mypy/binder.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,9 @@ def update_from_options(self, frames: list[Frame]) -> bool:
247247
type = possible_types[0]
248248
else:
249249
type = make_simplified_union(possible_types)
250+
# Legacy guard for corner case, e.g. when the original type is TypeVarType.
251+
if declaration_type is not None and not is_subtype(type, declaration_type):
252+
type = declaration_type
250253
# Try simplifying resulting type for unions involving variadic tuples.
251254
# Technically, everything is still valid without this step, but if we do
252255
# not do this, this may create long unions after exiting an if check like:

test-data/unit/check-narrowing.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2416,3 +2416,20 @@ while x is not None and b():
24162416
x = f()
24172417

24182418
[builtins fixtures/primitives.pyi]
2419+
2420+
[case testNarrowingTypeVarMultiple]
2421+
from typing import TypeVar
2422+
2423+
class A: ...
2424+
class B: ...
2425+
2426+
T = TypeVar("T")
2427+
def foo(x: T) -> T:
2428+
if isinstance(x, A):
2429+
pass
2430+
elif isinstance(x, B):
2431+
pass
2432+
else:
2433+
raise
2434+
return x
2435+
[builtins fixtures/isinstance.pyi]

0 commit comments

Comments
 (0)