typing_validation.validation
Core type validation functionality.
T
- T = ~T
Invariant type variable used by the functions
validatedandvalidated_iter.
UnsupportedTypeError
- class UnsupportedTypeError[source]
Bases:
ValueErrorClass for errors raised when attempting to validate an unsupported type.
Warning
Currently extends
ValueErrorfor backwards compatibility. This will be changed toNotImplementedErrorin v1.3.0.
can_validate
- can_validate(t)[source]
Checks whether validation is supported for the given type
t: if not,validatewill raiseUnsupportedTypeError.Warning
The return type will be changed to
boolin v1.3.0. To obtain aTypeInspectorobject, please use the newly introducedinspect_typeinstead.- Parameters:
t (
Any) – the type to be checked for validation support- Return type:
inspect_type
- inspect_type(t)[source]
Returns a
TypeInspectorinstance 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_typeproperty:>>> 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
TupleandListinstead oftupleandlistfor the above examples.- Parameters:
t (
Any) – the type to be checked for validation support- Return type:
is_valid
validate
- validate(val, t)[source]
Performs runtime type-checking for the value
valagainst typet. The function raisesTypeErrorupon failure and returnsTrueupon success. TheTruereturn value means thatvalidatecan 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
DictandListinstead ofdictandlistfor the above examples.- Parameters:
- Raises:
TypeError – if
valis not of typetUnsupportedTypeError – if validation for type
tis not supportedAssertionError – if things go unexpectedly wrong with
__args__for parametric types
- Return type:
Literal[True]
validated
- validated(val, t)[source]
Performs the same functionality as
validate, but returnsvalif 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)
validated_iter
- validated_iter(val, t)[source]
Performs the same functionality as
validated, but the iterablevaris wrapped into an iterator which validates its items prior to them being yielded.- Parameters:
val (
typing.Iterable[T])t (
Any)
- Return type:
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_aliasesto create a context wherevalidateinternally evaluates the forward reference"JSON"to the type aliasJSON:>>> 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: