validobj package

Module contents

Validobj gives you valid objects

Submodules

validobj.validation module

The validation module implements the parse_input() function.

validobj.validation.parse_input(value: Any, spec: Type[T]) → T

This is the main entry point of the validobj module. Validates and processes the input value based on the provided specification.

Parameters:
  • value (Any) – The value to be processed.
  • spec (type or typing specification) – The target specification.
Returns:

value – The processed form of value. This can be the input value itself if only a (recursive) type check was performed or a more structured output, based on the type of the specification.

Return type:

Any, compatible with spec

Raises:

ValidationError – Raised if the input cannot be coerced to the spec. An appropriate subclass defined in validobj.errors will contain more specific information as well __cause__ fields chained as neccessary.

Notes

The parameters are described in detail in Input and output.

The error handling is described in Errors.

Examples

Check that a given input is a mapping of string to integer:

>>> validobj.parse_input({'key1': 1, 'key2': 2}, typing.Mapping[str, int])
{'key1': 1, 'key2': 2}

Coerce the input to a dataclass of a valid shape:

>>> import dataclasses
>>> @dataclasses.dataclass
... class Data:
...     key: str
...     key2: int = 4
...
>>> validobj.parse_input({'key': 'Hello'}, Data)
Data(key='Hello', key2=4)

Find a list item that does not conform to the specification:

>>> import typing
>>> try:
...    validobj.parse_input([1,2,'tres'], typing.List[int])
... except validobj.ValidationError as e:
...    e.wrong_index
...
2

validobj.errors module

The errors module defines the exceptions raised by validobj.validation.parse_input() function. These are aleways subclasses of ValidationError.

exception validobj.errors.ValidationError

Bases: Exception

Exception raised when validation cannot be performed for any reason.

exception validobj.errors.UnionValidationError(*args, causes, **kwargs)

Bases: validobj.errors.ValidationError

Exception raised when value cannot be coerced to any of the members of an union.

Parameters:causes (List[ValidationError]) – A list of ValidationError exceptions containing the failure for each of the members of the union.
exception validobj.errors.WrongKeysError(missing, unknown, valid, header='')

Bases: validobj.errors.MismatchError

Error raised when the keys provided by the input do not match those required by the specification.

Parameters:
  • missing (set) – Keys that are required my the specification and missing in the input.
  • unknown (set) – Keys that are present in the input but unknown to the specification.
  • valid (set) – The set of all valid keys.
exception validobj.errors.WrongTypeError

Bases: validobj.errors.ValidationError, TypeError

Exception raised when some input is of the wrong type.

exception validobj.errors.NotAnEnumItemError(bad_item, enum_class)

Bases: validobj.errors.AlternativeDisplay, validobj.errors.ValidationError, ValueError

Exception raised when a string input is not an Enum name.

Parameters:
  • bad_item (str) – The value of the wrong item.
  • enum_class (type, enum.Enum subclass) – The enum class that does not contain bad_item
exception validobj.errors.WrongFieldError(*args, wrong_field, **kwargs)

Bases: validobj.errors.ValidationError

Exception raised when some field (e.g. in a mapping or dataclass) cannot be processed correctly.

Parameters:wrong_field (Any) – The key in the input mapping that caused the error.

Notes

The __cause__ attribute of the exception will contain the underlying reason for the error.

exception validobj.errors.WrongListItemError(*args, wrong_index, **kwargs)

Bases: validobj.errors.ValidationError

Exception raised when some item in a list cannot be processed correctly.

Parameters:wrong_index (int) – The index in the list that caused the error.

Notes

The __cause__ attribute of the exception will contain the underlying reason for the error.

validobj.custom module

Tools for custom validation of types.

class validobj.custom.InputType(type: Type)

Bases: object

A wrapper over an input type, for use in the custom processing.

Parameters:type (Type) – The wrapped type.
class validobj.custom.Validator(func: Callable)

Bases: object

A wrapper over a validation function, for use in the custom processing.

Parameters:func (Callable) – The wrapped function.
validobj.custom.Parser(func: Callable)

Read the type annotations of func and return a typing.Annotated with the function’s return type as the set type and the requisite metadata so that func is used by validobj.parse_input().

Parameters:func (Callable) – The wrapped function. It should have one positional parameter. If the parameter is annotated, Validobj will cast the input consitently with the annotation before presenting it to the function.
Returns:annotated – Annotation of the return type of the function with two metadata parameters: InputType with the type annotation of the first parameter and Validator with the function itself.
Return type:typing._AnnotatedAlias

Notes

While the returned annotation is compatible with static type checker, the runtime call to this function to produce it is not. Write the typing.Annotated manually if that is important.

Examples

Add support for decimal.Decimal.

>>> import typing
>>> import decimal
>>> from validobj import parse_input, ValidationError
>>> from validobj.custom import Parser
>>> def to_decimal(inp: typing.Union[str, int, float]) -> decimal.Decimal:
...     try:
...         return decimal.Decimal(inp)
...     except decimal.InvalidOperation as e:
...         raise ValidationError("Invalid decimal") from e
...
>>> Decimal = Parser(to_decimal)
>>> print(Decimal)
typing.Annotated[decimal.Decimal, InputType(typing.Union[str, int, float]), Validator(<function to_decimal at ...>)]
>>> parse_input(0.5, Decimal)
Decimal('0.5')