typing_validation.validation
Core type validation functionality.
T
- T = ~T
Invariant type variable used by the functions
validated
andvalidated_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 toNotImplementedError
in v1.3.0.
can_validate
- can_validate(t)[source]
Checks whether validation is supported for the given type
t
: if not,validate
will raiseUnsupportedTypeError
.Warning
The return type will be changed to
bool
in v1.3.0. To obtain aTypeInspector
object, please use the newly introducedinspect_type
instead.- Parameters:
t (
Any
) – the type to be checked for validation support- Return type:
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
andList
instead oftuple
andlist
for the above examples.- Parameters:
t (
Any
) – the type to be checked for validation support- Return type:
is_valid
- is_valid(val, t)[source]
Performs the same functionality as
validate
, but returningFalse
if validation is unsuccessful instead of raising error.In case of validation failure, detailed failure information is accessible via
latest_validation_failure
.
validate
- validate(val, t)[source]
Performs runtime type-checking for the value
val
against typet
. The function raisesTypeError
upon failure and returnsTrue
upon success. TheTrue
return value means thatvalidate
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
andList
instead ofdict
andlist
for the above examples.- Parameters:
- Raises:
TypeError – if
val
is not of typet
UnsupportedTypeError – if validation for type
t
is 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 returnsval
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)
validated_iter
- validated_iter(val, t)[source]
Performs the same functionality as
validated
, but the iterablevar
is 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_aliases
to create a context wherevalidate
internally 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: