predictably.validate.check_type#

predictably.validate.check_type(input_: Any, expected_type: type, allow_none: bool = False, input_name: str | None = None, use_subclass: bool = False) Any[source]#

Check the input is the expected type.

Validates that the input is the type specified in expected_type, while optionally allowing None values as well (if allow_none=True). For flexibility, the check can use issubclass instead of isinstance if use_subclass=True.

Parameters:
input_Any

The input to be type checked.

expected_typetype

The type that input_ is expected to be.

allow_nonebool, default=False

Whether input_ can be None in addition to being instance of expected_type.

input_namestr, default=None

The name to use when referring to input_ in any raised error messages. If None, then “input” is used as input_name.

use_subclassbool, default=False

Whether to check the type using issubclass instead of isinstance.

  • If True, then check uses issubclass.

  • If False (default), then check uses isinstance.

Returns:
Any

The input object.

Raises:
TypeError

If input does match expected type using isinstance by default or using issubclass in check if use_subclass=True.

Examples

>>> from predictably._core._base import BaseEstimator, BaseObject
>>> from predictably.validate import check_type
>>> check_type(7, expected_type=int)
7
>>> check_type(7.2, expected_type=(int, float))
7.2
>>> check_type(BaseEstimator(), BaseObject)
BaseEstimator()
>>> check_type(BaseEstimator, expected_type=BaseObject, use_subclass=True)
<class 'predictably._core._base.BaseEstimator'>

An error is raised if the input is not the expected type

>>> check_type(7, expected_type=str) 
TypeError: `input` should be type <class 'str'>, but found <class 'str'>.