mxutils.CheckType¶
-
mxutils.
CheckType
(item: Any, t: Optional[Union[Type, tuple]] = None, label: str | None = None) → Any¶ - Checks
item
for being of typet
.When the check fails, an error is being raised. If not,item
is being passed through. The function can automatically discover the symbol ofitem
when it is defined in the local or global scope of the function call.- Parameters
item (typing.Any) – The item to be type checked.
t (typing.Type | tuple[typing.Type] | None (, optional)) – The type or types
item
is allowed to be. PassingNone
will only assert thatitem
is notNone
. Defaults toNone
.label (str | None (, optional)) – The label with which to refer to
item
in exceptions. PassingNone
will result in an attempt to infer the symbol. Symbol discovery only works for values in the local or global scope. Defaults toNone
.
- Raises
TypeError – When
item
is failing the type test.RuntimeError – When accessing a stack trace or reading an executed file failed on a symbol discovery attempt.
- Returns
The value of
item
when the check succeeded.- Return type
typing.Any
- Example
import c4d import math from mxutils import CheckType MY_INT: int = 42 class Foo: SOME_INT: int = 42 def __init__(self, x: int) -> None: # Asserts that `x` is not `None`. CheckType(x) # Asserts that `x` is not `None` and assigns its values to `self._x`. self._x: object = CheckType(x) # Asserts that `MY_INT` is of type `int` or `float` and assigns its int value to `self._y`. self._y: int = int(CheckType(MY_INT, (int, float))) # Symbols which are neither in the global nor local scope are not automatically # discoverable and error messages for such values will refer to the value with # 'unknown symbol'. # `Foo.SOME_INT` and `math.pi` are not part of the local or global scope. When error # messages should not refer to a generic 'Unknown Symbol', one must pass in a label. # CheckType(Foo.SOME_INT, bool) # TypeError: Expected value of type <class 'bool'> for 'Unknown Symbol'. Received: <class 'int'> CheckType(math.pi, int, 'math.pi') # TypeError: Expected value of type <class 'int'> for 'math.pi'. Received: <class 'float'> # `x`, `y`, and `MY_INT` are in the global/local scope and automatically discovered. y: float = 1.0 CheckType(x, float) # TypeError: Expected value of type <class 'float'> for 'x'. Received: <class 'int'> CheckType(y, int) # TypeError: Expected value of type <class 'int'> for 'y'. Received: <class 'float'> CheckType(MY_INT, bool) # TypeError: Expected value of type <class 'bool'> for 'MY_INT'. Received: <class 'int'>