Skip to content

Type Utils

Type Utils

These are common utilities for types. They perform casting in the signature and check that the cast is valid.

extra_types.type_utils

strict_cast(typ, expr)

strict_cast(typ: type[_T], expr: Any) -> _T
strict_cast(typ: None, expr: Any) -> None
strict_cast(typ: object, expr: Any) -> Any

Determine whether an object is of a given type at runtime. This method is currently very limited in its ability to express types; as a result, it will produce false-positives, such as with Literal types. If the type does not match, this raises a TypeError.

Source code in extra_types/type_utils.py
def strict_cast(typ: object, expr: _T, /) -> Unmodified[_T]:
    """
    Determine whether an object is of a given type at runtime.
    This method is currently very limited in its ability to express types;
    as a result, it will produce false-positives, such as with `Literal` types.
    If the type does not match, this raises a `TypeError`.
    """
    if not _dynamic_type_check(typ, expr):
        raise TypeError(f"{expr} is not an instance of {typ}")
    return expr

strict_not_none(expr)

Check that an expression is not None. If it is None, this raises a TypeError.

Source code in extra_types/type_utils.py
def strict_not_none(expr: _T | None, /) -> Unmodified[_T]:
    """
    Check that an expression is not `None`.
    If it is `None`, this raises a `TypeError`.
    """
    if expr is None:
        raise TypeError(f"{expr} is {None}")
    return expr