maite.utils.validation.check_type#

maite.utils.validation.check_type(name, arg, type_, *, optional=False)[source]#

Check that an argument is an instance of one or more types.

Parameters:
namestr

The argument’s name.

argT (Any)

The argument.

type_type | tuple[type, …]

The type that arg should belong to. If multiple types are provided then checks that arg is an instance of at least one of them.

optionalbool, keyword, optional (default=False)

If True, then arg can be None.

Returns:
T

The input value, arg, unchanged.

Raises:
InvalidArgument

arg is not of the expected type.

Examples

>>> from maite.utils.validation import check_type
>>> check_type('apple', 1, int)
1
>>> try:
...     check_type('apple', 1, bool)
... except:
...     print("maite.errors.InvalidArgument: Expected `apple` to be of type `bool`. Got `1` (type: `int`).")
maite.errors.InvalidArgument: Expected `apple` to be of type `bool`. Got `1` (type: `int`).
>>> check_type('apple', 1, (int, bool))
1
>>> print(check_type('apple', None, (int, bool), optional=True))
None