Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
for x in narrowed.relevant_items()])
elif isinstance(narrowed, AnyType):
return narrowed
elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared):
return narrowed
elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):
return TypeType.make_normalized(narrow_declared_type(declared.item, narrowed.item))
elif (isinstance(declared, TypeType)
Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1073,3 +1073,23 @@ def f(t: Type[C]) -> None:
else:
reveal_type(t) # N: Revealed type is "Type[__main__.C]"
reveal_type(t) # N: Revealed type is "Type[__main__.C]"

[case testNarrowingUsingTypeVar]
# flags: --strict-optional
from typing import Type, TypeVar

class A: pass
class B(A): pass

T = TypeVar("T", bound=A)

def f(t: Type[T], a: A, b: B) -> None:
if type(a) is t:
reveal_type(a) # N: Revealed type is "T`-1"
else:
reveal_type(a) # N: Revealed type is "__main__.A"

if type(b) is t:
reveal_type(b) # N: Revealed type is "<nothing>"
else:
reveal_type(b) # N: Revealed type is "__main__.B"