typing_validation.validation

Core type validation functionality.

T

T = ~T

Invariant type variable used by the functions validated and validated_iter.

UnsupportedTypeError

class UnsupportedTypeError[source]

Bases: ValueError

Class for errors raised when attempting to validate an unsupported type.

Warning

Currently extends ValueError for backwards compatibility. This will be changed to NotImplementedError in v1.3.0.

can_validate

can_validate(t)[source]

Checks whether validation is supported for the given type t: if not, validate will raise UnsupportedTypeError.

Warning

The return type will be changed to bool in v1.3.0. To obtain a TypeInspector object, please use the newly introduced inspect_type instead.

Parameters:

t (Any) – the type to be checked for validation support

Return type:

TypeInspector

inspect_type

inspect_type(t)[source]

Returns a TypeInspector instance can be used wherever a boolean is expected, and will indicate whether the type is supported or not:

>>> from typing import *
>>> from typing_validation import inspect_type
>>> res = inspect_type(tuple[list[str], Union[int, float, Callable[[int], int]]])
>>> bool(res)
False

The instance also records (with minimal added cost) the full structure of the type as the latter was validated, which it then exposes via its TypeInspector.recorded_type property:

>>> res = inspect_type(tuple[list[Union[str, int]],...])
>>> bool(res)
True
>>> res.recorded_type
tuple[list[typing.Union[str, int]], ...]

Any unsupported subtype encountered during the validation is left in place, wrapped into an UnsupportedType:

>>> inspect_type(tuple[list[str], Union[int, float, Callable[[int], int]]])
The following type cannot be validated against:
tuple[
    list[
        str
    ],
    Union[
        int,
        float,
        UnsupportedType[
            typing.Callable[[int], int]
        ],
    ],
]

Note. For Python 3.7 and 3.8, use Tuple and List instead of tuple and list for the above examples.

Parameters:

t (Any) – the type to be checked for validation support

Return type:

TypeInspector

is_valid

is_valid(val, t)[source]

Performs the same functionality as validate, but returning False if validation is unsuccessful instead of raising error.

In case of validation failure, detailed failure information is accessible via latest_validation_failure.

Parameters:
  • val (T) –

  • t (Any) –

Return type:

bool

validate

validate(val, t)[source]

Performs runtime type-checking for the value val against type t. The function raises TypeError upon failure and returns True upon success. The True return value means that validate can be gated behind assertions and compiled away on optimised execution:

assert validate(val, t) # compiled away using -O and -OO

For structured types, the error message keeps track of the chain of validation failures, e.g.

>>> from typing import *
>>> from typing_validation import validate
>>> validate([[0, 1, 2], {"hi": 0}], list[Union[Collection[int], dict[str, str]]])
TypeError: Runtime validation error raised by validate(val, t), details below.
For type list[typing.Union[typing.Collection[int], dict[str, str]]], invalid value at idx: 1
For union type typing.Union[typing.Collection[int], dict[str, str]], invalid value: {'hi': 0}
    For member type typing.Collection[int], invalid value at idx: 0
    For type <class 'int'>, invalid value: 'hi'
    For member type dict[str, str], invalid value at key: 'hi'
    For type <class 'str'>, invalid value: 0

Note. For Python 3.7 and 3.8, use Dict and List instead of dict and list for the above examples.

Parameters:
  • val (Any) – the value to be type-checked

  • t (Any) – the type to type-check against

Raises:
Return type:

Literal[True]

validated

validated(val, t)[source]

Performs the same functionality as validate, but returns val if validation is successful.

Useful when multiple elements must be validated as part of a larger expression, e.g. as part of a comprehension:

def sortint(*items: int) -> list[int]:
    return sorted(validate(i) for i in items)
Parameters:
  • val (T) –

  • t (Any) –

Return type:

T

validated_iter

validated_iter(val, t)[source]

Performs the same functionality as validated, but the iterable var is wrapped into an iterator which validates its items prior to them being yielded.

Parameters:
Return type:

typing.Iterable[T]

validation_aliases

validation_aliases(**aliases)[source]

Sets type aliases that can be used to resolve forward references in validate.

For example, the following snippet validates a value against a recursive type alias for JSON-like objects, using validation_aliases to create a context where validate internally evaluates the forward reference "JSON" to the type alias JSON:

>>> JSON = Union[int, float, bool, None, str, list["JSON"], dict[str, "JSON"]]
>>> with validation_aliases(JSON=JSON):
>>>     validate([1, 2.2, {"a": ["Hello", None, {"b": True}]}], list["JSON"])
Parameters:

aliases (Any; variadic keyword) –

Return type:

collections.abc.Iterator[None]