Skip to content

Commit

Permalink
add tests for typevar narrowing changes
Browse files Browse the repository at this point in the history
  • Loading branch information
DetachHead committed Oct 6, 2024
1 parent 5ea940f commit 56f2fd5
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

def func1(v: Any) -> bool:
if isinstance(v, Iterable):
reveal_type(v, expected_text="Iterable[Unknown]")
reveal_type(v, expected_text="Iterable[object]")
if isinstance(v, Sized):
reveal_type(v, expected_text="<subclass of Iterable and Sized>")
reveal_type(v, expected_text="<subclass of Iterable[object] and Sized>")
return True
return False
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class ChildB1(ParentB[_T2]):

def func4(var: ParentB[int]):
if isinstance(var, ChildB1):
reveal_type(var, expected_text="ChildB1[int]")
reveal_type(var, expected_text="<subclass of ParentB[int] and ChildB1[float]>")


def func5(var: ParentB[Any]):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from typing import Never, assert_type, Iterable


class Covariant[T]:
def foo(self, other: object):
if isinstance(other, Covariant):
assert_type(other, Covariant[object])

def bar(self) -> T: ...

class CovariantByDefault[T]:
"""by default if there are no usages of a type var on a class, it's treated as covariant.
imo this should be an error. see https://github.com/DetachHead/basedpyright/issues/744"""
def foo(self, other: object):
if isinstance(other, CovariantByDefault):
assert_type(other, CovariantByDefault[object])

class CovariantWithBound[T: int | str]:
def foo(self, other: object):
if isinstance(other, CovariantWithBound):
assert_type(other, CovariantWithBound[int | str])

def bar(self) -> T: ...

class Contravariant[T]:
def foo(self, other: object):
if isinstance(other, Contravariant):
assert_type(other, Contravariant[Never])

def bar(self, other: T): ...

class ContravariantWithBound[T: int | str]:
def foo(self, other: object):
if isinstance(other, ContravariantWithBound):
assert_type(other, ContravariantWithBound[Never])

def bar(self, other: T): ...


def foo(value: object):
match value:
case Iterable():
assert_type(value, Iterable[object])
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,12 @@ test('subscript context manager types on 3.8', () => {
],
});
});

test('narrowing type vars to their bounds', () => {
const configOptions = new ConfigOptions(Uri.empty());
configOptions.diagnosticRuleSet.reportUnusedParameter = 'none';
const analysisResults = typeAnalyzeSampleFiles(['typeNarrowingToBounds.py'], configOptions);
validateResultsButBased(analysisResults, {
errors: [],
});
});

0 comments on commit 56f2fd5

Please sign in to comment.