Skip to content

Commit

Permalink
Fixed checking against a generic NewType
Browse files Browse the repository at this point in the history
Fixes #341.
  • Loading branch information
agronholm committed Apr 15, 2023
1 parent 46ddcc3 commit 4e347a4
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ This library adheres to `Semantic Versioning 2.0 <https://semver.org/#semantic-v
raised
- Fixed type checks for ``*args`` or ``**kwargs`` not being suppressed when their types
are unusable (guarded by ``if TYPE_CHECKING:`` or otherwise)
- Fixed ``TypeError`` when checking against a generic ``NewType``
- Don't try to check types shadowed by argument names (e.g.
``def foo(x: type, type: str): ...``)
- Don't check against unions where one of the elements is ``Any``
Expand Down
4 changes: 1 addition & 3 deletions src/typeguard/_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,9 +486,7 @@ def check_newtype(
args: tuple[Any, ...],
memo: TypeCheckMemo,
) -> None:
supertype = origin_type.__supertype__
if not isinstance(value, supertype):
raise TypeCheckError(f"is not an instance of {qualified_name(supertype)}")
check_type_internal(value, origin_type.__supertype__, memo)


def check_instance(
Expand Down
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class Employee(NamedTuple):

JSONType = Union[str, float, bool, None, List["JSONType"], Dict[str, "JSONType"]]
myint = NewType("myint", int)
mylist = NewType("mylist", List[int])


class FooGeneric(Generic[T_Foo]):
Expand Down
13 changes: 11 additions & 2 deletions tests/test_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
TParent,
TTypingConstrained,
myint,
mylist,
)

if sys.version_info >= (3, 11):
Expand Down Expand Up @@ -757,14 +758,22 @@ def test_constraints_fail(self):


class TestNewType:
def test_valid(self):
def test_simple_valid(self):
check_type(1, myint)

def test_bad_value(self):
def test_simple_bad_value(self):
pytest.raises(TypeCheckError, check_type, "a", myint).match(
r"str is not an instance of int"
)

def test_generic_valid(self):
check_type([1], mylist)

def test_generic_bad_value(self):
pytest.raises(TypeCheckError, check_type, ["a"], mylist).match(
r"item 0 of list is not an instance of int"
)


class TestType:
@pytest.mark.parametrize("annotation", [pytest.param(Type), pytest.param(type)])
Expand Down

0 comments on commit 4e347a4

Please sign in to comment.