Skip to content

Commit

Permalink
Added support for passing a tuple as expected_type to check_type()
Browse files Browse the repository at this point in the history
Closes #371.
  • Loading branch information
agronholm committed Jul 29, 2023
1 parent 6a5b8e2 commit 0141f43
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
3 changes: 3 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ This library adheres to `Semantic Versioning 2.0 <https://semver.org/#semantic-v

**UNRELEASED**

- Added support for passing a tuple as ``expected_type`` to ``check_type()``, making it
more of a drop-in replacement for ``isinstance()``
(`#371 <https://github.com/agronholm/typeguard/issues/371>`_
- Fixed regression where ``Literal`` inside a ``Union`` had quotes stripped from its
contents, thus typically causing ``NameError`` to be raised when run
(`#372 <https://github.com/agronholm/typeguard/issues/372>`_)
Expand Down
7 changes: 5 additions & 2 deletions src/typeguard/_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys
import warnings
from typing import Any, Callable, NoReturn, TypeVar, overload
from typing import Any, Callable, NoReturn, TypeVar, Union, overload

from . import _suppression
from ._checkers import BINARY_MAGIC_METHODS, check_type_internal
Expand Down Expand Up @@ -80,7 +80,7 @@ def check_type(
corresponding fields in :class:`TypeCheckConfiguration`.
:param value: value to be checked against ``expected_type``
:param expected_type: a class or generic type instance
:param expected_type: a class or generic type instance, or a tuple of such things
:param forward_ref_policy: see :attr:`TypeCheckConfiguration.forward_ref_policy`
:param typecheck_fail_callback:
see :attr`TypeCheckConfiguration.typecheck_fail_callback`
Expand All @@ -90,6 +90,9 @@ def check_type(
:raises TypeCheckError: if there is a type mismatch
"""
if type(expected_type) is tuple:
expected_type = Union[expected_type]

config = TypeCheckConfiguration(
forward_ref_policy=forward_ref_policy,
typecheck_fail_callback=typecheck_fail_callback,
Expand Down
8 changes: 8 additions & 0 deletions tests/test_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1080,3 +1080,11 @@ def test_imported_str_forward_ref():
pattern = r"Skipping type check against 'Dict\[str, int\]'"
with pytest.warns(TypeHintWarning, match=pattern):
check_type_internal(value, "Dict[str, int]", memo)


def test_check_against_tuple_success():
check_type(1, (float, Union[str, int]))


def test_check_against_tuple_failure():
pytest.raises(TypeCheckError, check_type, "aa", (int, bytes))

0 comments on commit 0141f43

Please sign in to comment.