koda_validate¶
- class AlwaysValid¶
Whatever value is submitted for validation will be returned as valid
- class BoolValidator(*predicates, predicates_async=None, preprocessors=None, coerce=None)¶
Validate a value is a
bool, and any extra refinement.If
predicates_asyncis supplied, the__call__method should not be called – only.validate_asyncshould be used.- Parameters:
predicates (
Predicate[TypeVar(SuccessT)]) – any number ofPredicate[bool]instancespredicates_async (
Optional[list[PredicateAsync[TypeVar(SuccessT)]]], default:None) – any number ofPredicateAsync[bool]instancespreprocessors (
Optional[list[Processor[TypeVar(SuccessT)]]], default:None) – any number ofProcessor[bool], which will be run beforePredicates andPredicateAsyncs are checked.coerce (
Optional[Coercer[TypeVar(SuccessT)]], default:None) – a function that can control coercion
- class BytesValidator(*predicates, predicates_async=None, preprocessors=None, coerce=None)¶
Validate a value is a
bytes, and any extra refinement.If
predicates_asyncis supplied, the__call__method should not be called – only.validate_asyncshould be used.Example:
>>> from koda_validate import * >>> validator = BytesValidator(not_blank, MaxLength(100), preprocessors=[strip]) >>> validator(b"") Invalid( err_type=PredicateErrs(predicates=[ NotBlank(), ]), value=b'', validator=BytesValidator(NotBlank(), MaxLength(length=100), preprocessors=[Strip()]) ) >>> validator("") Invalid( err_type=TypeErr(expected_type=<class 'bytes'>), value='', validator=BytesValidator(NotBlank(), MaxLength(length=100), preprocessors=[Strip()]) ) >>> validator(b' ok ') Valid(val=b'ok')
- Parameters:
predicates (
Predicate[TypeVar(SuccessT)]) – any number ofPredicate[bytes]instancespredicates_async (
Optional[list[PredicateAsync[TypeVar(SuccessT)]]], default:None) – any number ofPredicateAsync[bytes]instancespreprocessors (
Optional[list[Processor[TypeVar(SuccessT)]]], default:None) – any number ofProcessor[bytes], which will be run beforePredicates andPredicateAsyncs are checked.coerce (
Optional[Coercer[TypeVar(SuccessT)]], default:None) – a function that can control coercion
- class CacheValidatorBase(validator)¶
This class should be subclassed to work with whatever caching configuration is desired
- __call__(val)¶
- async cache_get_async(val)¶
Try to get a value from a cache asynchronously and return
Maybe[ValidationResult[A]]
- cache_get_sync(val)¶
Try to get a value from a cache and return
Maybe[ValidationResult[A]]
- async cache_set_async(val, cache_val)¶
- Return type:
None
- cache_set_sync(val, cache_val)¶
- Return type:
None
- async validate_async(val)¶
- validator¶
- class Choices(choices)¶
A allow to check some
Hashabletype against a finite set of values.- __call__(val)¶
- Parameters:
val (
TypeVar(ChoiceT, bound=Hashable)) – the value being validated- Return type:
bool
- choices¶
- class Coercer(coerce, compatible_types)¶
- __call__(val)¶
Call self as a function.
- Return type:
Union[Just[TypeVar(A)],Nothing]
- coerce¶
The function which handles the coercion.
- compatible_types¶
All the types which can potentially be coerced.
- class CoercionErr(compatible_types, dest_type)¶
Similar to a TypeErr, but when one or more types can be coerced to a destination type
- compatible_types¶
- dest_type¶
- class DataclassValidator(data_cls, *, overrides=None, validate_object=None, validate_object_async=None, fail_on_unknown_keys=False, typehint_resolver=<function get_typehint_validator>, coerce=None)¶
Takes a
dataclassas an argument and derives aValidator. Will validate against an instance ofself.data_clsor a dictionary. Regardless of the input type, the result will be an instance of typeself.data_cls.Optional keys are determined by the presence of a default argument.
Example:
from dataclasses import dataclass from koda_validate import * @dataclass class Person: name: str hobbies: list[str] validator = DataclassValidator(Person)
Usage:
>>> validator({"name": "Bob", "hobbies": ["eating", "coding", "sleeping"]}) Valid(val=Person(name='Bob', hobbies=['eating', 'coding', 'sleeping']))
- Parameters:
data_cls (
Type[TypeVar(_DCT, bound=DataclassLike)]) – Adataclassclassoverrides (
Optional[dict[str,Validator[Any]]], default:None) – a dict whose keys define explicit validatorsvalidate_object (
Optional[Callable[[TypeVar(_DCT, bound=DataclassLike)],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]], default:None) – is run if all keys have been validated individually. If it returnsNone, then there were no errors; otherwise it should returnErrTypevalidate_object_async (
Optional[Callable[[TypeVar(_DCT, bound=DataclassLike)],Awaitable[Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]]], default:None) – same asvalidate_object, except that is runs asynchronouslytypehint_resolver (
Callable[[Any],Validator[Any]], default:<function get_typehint_validator at 0x7e4eba4e8400>) – define this to override default inferred validators for typesfail_on_unknown_keys (
bool, default:False) – if True, this will fail if any keys not defined byself.data_clsare found. This will fail before any values are validated.coerce (
Optional[Coercer[dict[Any,Any]]], default:None) – a function that can control coercion
- Raises:
TypeError – should raise if non-
dataclasstype is passed fordata_cls
- class DateValidator(*predicates, predicates_async=None, preprocessors=None, coerce=Coercer(coerce=<function coerce_date>, compatible_types={<class 'str'>, <class 'datetime.date'>}))¶
- class DatetimeValidator(*predicates, predicates_async=None, preprocessors=None, coerce=Coercer(coerce=<function coerce_datetime>, compatible_types={<class 'datetime.datetime'>, <class 'str'>}))¶
- class DecimalValidator(*predicates, predicates_async=None, preprocessors=None, coerce=Coercer(coerce=<function coerce_decimal>, compatible_types={<class 'int'>, <class 'str'>, <class 'decimal.Decimal'>}))¶
- class DictValidatorAny(schema, *, validate_object=None, validate_object_async=None, fail_on_unknown_keys=False)¶
This class exists for a few reasons:
it can handle an arbitrary amount of keys, of any combination of hashable types
it’s initialization is very straightforward
The big caveat is that a valid result is always typed as
dict[Any, Any], even though the validation will work just as well as with any otherValidator
- class EmailPredicate(pattern=re.compile('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+'))¶
- __call__(val)¶
- Parameters:
val (
str) – the value being validated- Return type:
bool
- pattern = re.compile('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+')¶
- class EndsWith(suffix)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- suffix¶
- class EqualTo(match)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(ExactMatchT,bool,bytes,int,Decimal,str,float,date,datetime,UUID)) – the value being validated- Return type:
bool
- match¶
- class EqualsValidator(match, preprocessors=None)¶
Check if a value is of the same type as
matchand check that that value is equivalent.- match¶
- preprocessors = None¶
- class ExactItemCount(item_count)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(ListOrTupleOrSetAny,list[Any],tuple[Any,...],set[Any])) – the value being validated- Return type:
bool
- item_count¶
- class ExactLength(length)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- length¶
- class FloatValidator(*predicates, predicates_async=None, preprocessors=None, coerce=None)¶
Validate a value is a
float, and any extra refinement.If
predicates_asyncis supplied, the__call__method should not be called – only.validate_asyncshould be used.- Parameters:
predicates (
Predicate[TypeVar(SuccessT)]) – any number ofPredicate[float]instancespredicates_async (
Optional[list[PredicateAsync[TypeVar(SuccessT)]]], default:None) – any number ofPredicateAsync[float]instancespreprocessors (
Optional[list[Processor[TypeVar(SuccessT)]]], default:None) – any number ofProcessor[float], which will be run beforePredicates andPredicateAsyncs are checked.coerce (
Optional[Coercer[TypeVar(SuccessT)]], default:None) – a function that can control coercion
- class IntValidator(*predicates, predicates_async=None, preprocessors=None, coerce=None)¶
Validate a value is a
int, and any extra refinement.If
predicates_asyncis supplied, the__call__method should not be called – only.validate_asyncshould be used.- Parameters:
predicates (
Predicate[TypeVar(SuccessT)]) – any number ofPredicate[int]instancespredicates_async (
Optional[list[PredicateAsync[TypeVar(SuccessT)]]], default:None) – any number ofPredicateAsync[int]instancespreprocessors (
Optional[list[Processor[TypeVar(SuccessT)]]], default:None) – any number ofProcessor[int], which will be run beforePredicates andPredicateAsyncs are checked.coerce (
Optional[Coercer[TypeVar(SuccessT)]], default:None) – a function that can control coercion
- class Invalid(err_type, value, validator)¶
Represents validation failure. Contains relevant failure data so use case-specific error objects (or other data) can be produced.
- err_type¶
Any of a number of classes that contain data about the type of error, e.g.
TypeErr,CoercionErr,KeyMissingErr, etc.
- is_valid = False¶
This is always
FalseonInvalidinstances. It’s useful forifstatements. Mypy understands it as a tag for a tagged union.
- validator¶
The validator that determined
valueto be invalid
- value¶
The invalid value that was being validated
- class IsDictValidator¶
- class KeyValErrs(key, val)¶
Key and/or value errors from a single key/value pair. This is useful for mapping collections.
- key¶
- val¶
- class Lazy(validator, recurrent=True)¶
Allows for specification of mutually recursive type definitions.
- __call__(data)¶
- class ListValidator(item_validator, *, predicates=None, predicates_async=None, coerce=None)¶
- class LowerCase¶
- __call__(val)¶
Call self as a function.
- Return type:
TypeVar(StrOrBytes,str,bytes)
- class MapValidator(*, key, value, predicates=None, predicates_async=None, coerce=None)¶
- __call__(val)¶
- class Max(maximum, exclusive_maximum=False)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(MinMaxT,int,float,Decimal,date,datetime)) – the value being validated- Return type:
bool
- exclusive_maximum = False¶
- maximum¶
- class MaxItems(item_count)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(ListOrTupleOrSetAny,list[Any],tuple[Any,...],set[Any])) – the value being validated- Return type:
bool
- item_count¶
- class MaxKeys(size)¶
- __call__(val)¶
- Parameters:
val (
dict[Any,Any]) – the value being validated- Return type:
bool
- size¶
- class MaxLength(length)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- length¶
- class Min(minimum, exclusive_minimum=False)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(MinMaxT,int,float,Decimal,date,datetime)) – the value being validated- Return type:
bool
- exclusive_minimum = False¶
- minimum¶
- class MinItems(item_count)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(ListOrTupleOrSetAny,list[Any],tuple[Any,...],set[Any])) – the value being validated- Return type:
bool
- item_count¶
- class MinKeys(size)¶
- __call__(val)¶
- Parameters:
val (
dict[Any,Any]) – the value being validated- Return type:
bool
- size¶
- class MinLength(length)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- length¶
- class MissingKeyErr¶
A key is missing from a dictionary
- class MultipleOf(factor)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(Num,int,float,Decimal)) – the value being validated- Return type:
bool
- factor¶
- class NTupleValidator(*, fields, validate_object=None, coerce=Coercer(coerce=<function tuple_or_list_to_tuple>, compatible_types={<class 'list'>, <class 'tuple'>}))¶
- static typed(*, fields, validate_object=None, coerce=Coercer(coerce=<function tuple_or_list_to_tuple>, compatible_types={<class 'list'>, <class 'tuple'>}))¶
Can be used for up to 8 typed tuple slots. For more than 8 slots, use
NTupleValidator.untyped.- Parameters:
fields (
Union[tuple[Validator[TypeVar(T1)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)],Validator[TypeVar(T4)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)],Validator[TypeVar(T4)],Validator[TypeVar(T5)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)],Validator[TypeVar(T4)],Validator[TypeVar(T5)],Validator[TypeVar(T6)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)],Validator[TypeVar(T4)],Validator[TypeVar(T5)],Validator[TypeVar(T6)],Validator[TypeVar(T7)]],tuple[Validator[TypeVar(T1)],Validator[TypeVar(T2)],Validator[TypeVar(T3)],Validator[TypeVar(T4)],Validator[TypeVar(T5)],Validator[TypeVar(T6)],Validator[TypeVar(T7)],Validator[TypeVar(T8)]]]) – a tuple the validators to be used, whose types will reflect the resulting tuplevalidate_object (
Union[Callable[[tuple[TypeVar(T1)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],None,Callable[[tuple[TypeVar(T1),TypeVar(T2)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]],Callable[[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7),TypeVar(T8)]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]], default:None) – a function which can be used to validate the tuple after individual slots have been validatedcoerce (
Optional[Coercer[Tuple[Any,...]]], default:Coercer(coerce=<function tuple_or_list_to_tuple at 0x7e4eba4c6b60>, compatible_types={<class 'list'>, <class 'tuple'>})) – control coercion prior to validation
- Return type:
Union[NTupleValidator[Tuple[TypeVar(T1)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7)]],NTupleValidator[Tuple[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7),TypeVar(T8)]]]- Returns:
NTupleValidatorwith thefieldsas defined by thefieldsparameter
- static untyped(*, fields, validate_object=None, coerce=Coercer(coerce=<function tuple_or_list_to_tuple>, compatible_types={<class 'list'>, <class 'tuple'>}))¶
Identical to NTupleValidator.typed except that it can be used for an arbitrary number of slots. Does not retain type information.
- Parameters:
fields (
Tuple[Validator[Any],...]) – a tuple the validators to be used, whose types will reflect the resulting tuplevalidate_object (
Optional[Callable[[Tuple[Any,...]],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]], default:None) – a function which can be used to validate the tuple after individual slots have been validatedcoerce (
Optional[Coercer[Tuple[Any,...]]], default:Coercer(coerce=<function tuple_or_list_to_tuple at 0x7e4eba4c6b60>, compatible_types={<class 'list'>, <class 'tuple'>})) – control coercion prior to validation
- Return type:
NTupleValidator[Tuple[Any,...]]- Returns:
NTupleValidatorwith thefieldsas defined by thefieldsparameter
- class NamedTupleValidator(named_tuple_cls, *, overrides=None, validate_object=None, validate_object_async=None, fail_on_unknown_keys=False, typehint_resolver=<function get_typehint_validator>, coerce=None)¶
Takes a
NamedTuplesubclass as an argument and derives aValidator. Will validate against an instance ofself.named_tuple_clsor a dictionary. Regardless of the input type, the result will be an instance of typeself.named_tuple_cls.Optional keys are determined by the presence of a default argument.
Example:
from dataclasses import dataclass from typing import NamedTuple from koda_validate import * class Person(NamedTuple): name: str hobbies: list[str] validator = NamedTupleValidator(Person)
Usage:
>>> validator({"name": "Bob", "hobbies": ["eating", "coding", "sleeping"]}) Valid(val=Person(name='Bob', hobbies=['eating', 'coding', 'sleeping']))
- Parameters:
named_tuple_cls (
Type[TypeVar(_NTT, bound=NamedTuple)]) – Adataclassclassoverrides (
Optional[dict[str,Validator[Any]]], default:None) – a dict whose keys define explicit validatorsvalidate_object (
Optional[Callable[[TypeVar(_NTT, bound=NamedTuple)],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]], default:None) – is run if all keys have been validated individually. If it returnsNone, then there were no errors; otherwise it should returnErrTypevalidate_object_async (
Optional[Callable[[TypeVar(_NTT, bound=NamedTuple)],Awaitable[Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]]], default:None) – same asvalidate_object, except that is runs asynchronouslytypehint_resolver (
Callable[[Any],Validator[Any]], default:<function get_typehint_validator at 0x7e4eba4e8400>) – define this to override default inferred validators for typesfail_on_unknown_keys (
bool, default:False) – if True, this will fail if any keys not defined byself.data_clsare found. This will fail before any values are validated.coerce (
Optional[Coercer[dict[Any,Any]]], default:None) – a function that can control coercion
- Raises:
TypeError – should raise if non-
NamedTupletype is passed fornamed_tuple_cls
- class NotBlank¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- class OptionalValidator(validator, *, none_validator=NoneValidator(coerce=None))¶
We have a value for a key, but it can be null (None)
- class Predicate¶
A predicate just returns
TrueorFalsefor some condition.Predicates can be used during async validation, butPredicateAsyncshould be used for any validation that requiresasyncio.Example
Predicate:from koda_validate import Predicate class GreaterThan(Predicate[int]): def __init__(self, limit: int) -> None: self.limit = limit def __call__(self, val: int) -> bool: return val > self.limit
Usage
>>> gt = GreaterThan(5) >>> gt(6) True >>> gt(1) False
- abstract __call__(val)¶
- Parameters:
val (
TypeVar(A)) – the value being validated- Return type:
bool
- class PredicateAsync¶
The async-only sibling of
Predicate.Example
PredicateAsyncimport asyncio from koda_validate import PredicateAsync class UsernameInDB(PredicateAsync[str]): async def validate_async(self, val: str) -> bool: # pretend to call db await asyncio.sleep(.001) # dummy logic for example return len(val) == 3
Usage
>>> asyncio.run(UsernameInDB().validate_async("abc")) True >>> asyncio.run(UsernameInDB().validate_async("abcdef")) False
- abstract async validate_async(val)¶
- Parameters:
val (
TypeVar(A)) – the value being validated- Return type:
bool- Returns:
a bool indicating whether the condition is
Truefor the value
- class Processor¶
Base class for
Processors. These are litle more thanCallable[[A], A]
They transform a value of one type to another value of the same type. The are useful for things like
strip-ping strings:from dataclasses import dataclass from koda_validate import Processor @dataclass class Strip(Processor[str]): def __call__(self, val: str) -> str: return val.strip()
Usage:
>>> strip = Strip() >>> strip(" abc ") 'abc' >>> strip("def") 'def'
Note
Because processors are type-aware they are most useful directly after type verification or coercion.
- abstract __call__(val)¶
Call self as a function.
- Return type:
TypeVar(A)
- class RecordValidator(into, keys, validate_object=None, validate_object_async=None, fail_on_unknown_keys=False)¶
- class RegexPredicate(pattern)¶
- __call__(val)¶
- Parameters:
val (
str) – the value being validated- Return type:
bool
- pattern¶
- class SetValidator(item_validator, *, predicates=None, predicates_async=None, coerce=None)¶
- class StartsWith(prefix)¶
- __call__(val)¶
- Parameters:
val (
TypeVar(StrOrBytes,str,bytes)) – the value being validated- Return type:
bool
- prefix¶
- class StringValidator(*predicates, predicates_async=None, preprocessors=None, coerce=None)¶
Validate a value is a
str, and any extra refinement.If
predicates_asyncis supplied, the__call__method should not be called – only.validate_asyncshould be used.Example:
>>> from koda_validate import * >>> validator = StringValidator(not_blank, MaxLength(100), preprocessors=[strip]) >>> validator("") Invalid( err_type=PredicateErrs(predicates=[ NotBlank(), ]), value='', validator=StringValidator(NotBlank(), MaxLength(length=100), preprocessors=[Strip()]) ) >>> validator(None) Invalid( err_type=TypeErr(expected_type=<class 'str'>), value=None, validator=StringValidator(NotBlank(), MaxLength(length=100), preprocessors=[Strip()]) ) >>> validator(" ok ") Valid(val='ok')
- Parameters:
predicates (
Predicate[TypeVar(SuccessT)]) – any number ofPredicate[str]instancespredicates_async (
Optional[list[PredicateAsync[TypeVar(SuccessT)]]], default:None) – any number ofPredicateAsync[str]instancespreprocessors (
Optional[list[Processor[TypeVar(SuccessT)]]], default:None) – any number ofProcessor[str], which will be run beforePredicates andPredicateAsyncs are checked.
- class TypedDictValidator(td_cls, *, overrides=None, validate_object=None, validate_object_async=None, coerce=None, typehint_resolver=<function get_typehint_validator>, fail_on_unknown_keys=False)¶
Takes a
TypedDictsubclass as an argument and derives aValidator.Optional keys are determined by the
__optional_keys__and__required_keys__attributes.Note
This validator _might_ work on non-typed-dict classes (There are challenges in defining a TypedDict-like type). Please do not intentionally try to use it for non-TypedDict datatypes.
Example:
from typing import TypedDict from koda_validate import * class Person(TypedDict): name: str hobbies: list[str] validator = TypedDictValidator(Person)
Usage:
>>> validator({"name": "Bob", "hobbies": ["eating", "coding", "sleeping"]}) Valid(val={'name': 'Bob', 'hobbies': ['eating', 'coding', 'sleeping']})
- Parameters:
td_cls (
Type[TypeVar(_TDT, bound=Mapping[str,object])]) – ATypedDictsubclassoverrides (
Optional[dict[str,Validator[Any]]], default:None) – a dict whose keys define explicit validatorsvalidate_object (
Optional[Callable[[TypeVar(_TDT, bound=Mapping[str,object])],Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]], default:None) – is run if all keys have been validated individually. If it returnsNone, then there were no errors; otherwise it should returnErrTypevalidate_object_async (
Optional[Callable[[TypeVar(_TDT, bound=Mapping[str,object])],Awaitable[Union[CoercionErr,ContainerErr,ExtraKeysErr,IndexErrs,KeyErrs,MapErr,MissingKeyErr,PredicateErrs[Any],SetErrs,TypeErr,ValidationErrBase,UnionErrs,None]]]], default:None) – same asvalidate_object, except that is runs asynchronouslytypehint_resolver (
Callable[[Any],Validator[Any]], default:<function get_typehint_validator at 0x7e4eba4e8400>) – define this to override default inferred validators for typescoerce (
Optional[Coercer[dict[Any,Any]]], default:None) – this can be set to create any kind of custom coercionfail_on_unknown_keys (
bool, default:False) – if True, this will fail if any keys not defined by theTypedDictare found. This will fail before any values are validated.
- Raises:
TypeError – should raise if non-
TypedDicttype is passed fortd_cls
- class UUIDValidator(*predicates, predicates_async=None, preprocessors=None, coerce=Coercer(coerce=<function coerce_uuid>, compatible_types={<class 'str'>, <class 'uuid.UUID'>}))¶
- class UniformTupleValidator(item_validator, *, predicates=None, predicates_async=None, coerce=Coercer(coerce=<function tuple_or_list_to_tuple>, compatible_types={<class 'list'>, <class 'tuple'>}))¶
- class UnionValidator(validator_1, *validators)¶
- static typed(validator_1, validator_2=None, validator_3=None, validator_4=None, validator_5=None, validator_6=None, validator_7=None, validator_8=None)¶
Can be used for up to 8 typed variants. For more than 8 variants, use
UnionValidator.untyped. Arguments should be positional only. (@overloadsspecify that arguments should be positional-only.)- Parameters:
validator_1 (
Validator[TypeVar(T1)]) – the first variantvalidator_2 (
Optional[Validator[TypeVar(T2)]], default:None) – the second variant (if defined)validator_3 (
Optional[Validator[TypeVar(T3)]], default:None) – the third variant (if defined)validator_4 (
Optional[Validator[TypeVar(T4)]], default:None) – the fourth variant (if defined)validator_5 (
Optional[Validator[TypeVar(T5)]], default:None) – the fifth variant (if defined)validator_6 (
Optional[Validator[TypeVar(T6)]], default:None) – the sixth variant (if defined)validator_7 (
Optional[Validator[TypeVar(T7)]], default:None) – the seventh variant (if defined)validator_8 (
Optional[Validator[TypeVar(T8)]], default:None) – the eighth variant (if defined)
- Return type:
Union[UnionValidator[TypeVar(T1)],UnionValidator[Union[TypeVar(T1),TypeVar(T2)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7)]],UnionValidator[Union[TypeVar(T1),TypeVar(T2),TypeVar(T3),TypeVar(T4),TypeVar(T5),TypeVar(T6),TypeVar(T7),TypeVar(T8)]]]- Returns:
UnionValidator with the variants defined above.
- static untyped(validator_1, *validators)¶
Can handle any number of variant
Validator<koda_validate.Validator>`s (as opposed toUnionValidator.typed), but does not retain type information.- Parameters:
- Return type:
UnionValidator[Any]- Returns:
UnionValidator with the variants defined above.
- class UniqueItems¶
Works with both hashable and unhashable items.
- __call__(val)¶
- Parameters:
val (
TypeVar(ListOrTupleOrSetAny,list[Any],tuple[Any,...],set[Any])) – the value being validated- Return type:
bool
- class UpperCase¶
- __call__(val)¶
Call self as a function.
- Return type:
TypeVar(StrOrBytes,str,bytes)
- class Valid(val)¶
A wrapper for valid data, e.g.
Valid("abc")- is_valid = True¶
This is always
TrueonValidinstances. It’s useful forifstatements. Mypy understands it as a tag for a tagged union.
- val¶
The value that has succeeded validation
- class ValidationErrBase¶
This class exists only to provide a class to subclass for custom error types
- class Validator¶
Base class for all
Validators.It’s little more than a
Callable[[Any], ValidationResult[SuccessT]], with two notable differences:- A
.validate_asyncmethod is allowed, meaning aValidatorcan be made to work in both sync and async contexts.
- A
Validator`s are ``class`es. ConstructingCallableclasses allowsus to more easily make metadata from the validator available (as opposed to data being hidden inside a closure)
Depending on your use case, you may want to implement the
__call__method, theasync_validatemethod, or both.Note
Fundamentally,
Validators need to be able to return valid data that is a different type than what was passed in. The main reason for this is that we need to be able to call aValidatorwith data of unknown types. For that reasonValidators acceptAnyas input. This has a few notable implications:- __call__(val)¶
- coercer(*compatible_types)¶
This is purely a convenience constructor for
Coercerobjects.- Parameters:
compatible_types (
Type[Any]) – the types the coercer can take to produce an the return type- Return type:
Callable[[Callable[[Any],Union[Just[TypeVar(A)],Nothing]]],Coercer[TypeVar(A)]]- Returns:
A callable which accepts a function that should be congruent with the
compatible_typesparam.
- ErrType¶
alias of
CoercionErr|ContainerErr|ExtraKeysErr|IndexErrs|KeyErrs|MapErr|MissingKeyErr|PredicateErrs[Any] |SetErrs|TypeErr|ValidationErrBase|UnionErrs