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_async
is supplied, the__call__
method should not be called – only.validate_async
should 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 beforePredicate
s andPredicateAsync
s 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_async
is supplied, the__call__
method should not be called – only.validate_async
should be used.Example:
>>> from koda_validate import * >>> validator = BytesValidator(not_blank, MaxLength(100), preprocessors=[strip]) >>> validator(b"") Invalid(err_type=PredicateErrs(predicates=[NotBlank()]), ...) >>> validator("") Invalid(err_type=TypeErr(expected_type=<class 'bytes'>), ...) >>> 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 beforePredicate
s andPredicateAsync
s 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
Hashable
type 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
dataclass
as an argument and derives aValidator
. Will validate against an instance ofself.data_cls
or 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 typing import List 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
)]) – Adataclass
classoverrides (
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 returnErrType
validate_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 0x7fa8194d2c00>
) – 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_cls
are 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-
dataclass
type 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
match
and check that that value is equivalent.- match#
- preprocessors = None#
- class ExactItemCount(item_count)#
- __call__(val)#
- Parameters:
val (
Sized
) – 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_async
is supplied, the__call__
method should not be called – only.validate_async
should 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 beforePredicate
s andPredicateAsync
s 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_async
is supplied, the__call__
method should not be called – only.validate_async
should 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 beforePredicate
s andPredicateAsync
s 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
False
onInvalid
instances. It’s useful forif
statements. Mypy understands it as a tag for a tagged union.
- validator#
The validator that determined
value
to 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 0x7fa8194d13a0>, 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:
NTupleValidator
with thefields
as defined by thefields
parameter
- 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 0x7fa8194d13a0>, compatible_types={<class 'list'>, <class 'tuple'>})
) – control coercion prior to validation
- Return type:
NTupleValidator
[Tuple
[Any
,...
]]- Returns:
NTupleValidator
with thefields
as defined by thefields
parameter
- 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
NamedTuple
subclass as an argument and derives aValidator
. Will validate against an instance ofself.named_tuple_cls
or 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 List, 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
)]) – Adataclass
classoverrides (
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 returnErrType
validate_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 0x7fa8194d2c00>
) – 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_cls
are 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-
NamedTuple
type 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
True
orFalse
for some condition.Predicate
s can be used during async validation, butPredicateAsync
should 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
PredicateAsync
import 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
True
for the value
- class Processor#
Base class for
Processor
s. 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_async
is supplied, the__call__
method should not be called – only.validate_async
should be used.Example:
>>> from koda_validate import * >>> validator = StringValidator(not_blank, MaxLength(100), preprocessors=[strip]) >>> validator("") Invalid(err_type=PredicateErrs(predicates=[NotBlank()]), ...) >>> validator(None) Invalid(err_type=TypeErr(expected_type=<class 'str'>), ...) >>> 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 beforePredicate
s andPredicateAsync
s 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
TypedDict
subclass 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 List, 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
])]) – ATypedDict
subclassoverrides (
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 returnErrType
validate_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 0x7fa8194d2c00>
) – 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 theTypedDict
are found. This will fail before any values are validated.
- Raises:
TypeError – should raise if non-
TypedDict
type 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. (@overloads
specify 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
True
onValid
instances. It’s useful forif
statements. 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
Validator
s.It’s little more than a
Callable[[Any], ValidationResult[SuccessT]]
, with two notable differences:- A
.validate_async
method is allowed, meaning aValidator
can be made to work in both sync and async contexts.
- A
Validator`s are ``class`
es. ConstructingCallable
class
es 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_validate
method, or both.Note
Fundamentally,
Validator
s 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 aValidator
with data of unknown types. For that reasonValidator
s acceptAny
as input. This has a few notable implications:- __call__(val)#
- coercer(*compatible_types)#
This is purely a convenience constructor for
Coercer
objects.- 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_types
param.
- ErrType#
alias of
Union
[CoercionErr
,ContainerErr
,ExtraKeysErr
,IndexErrs
,KeyErrs
,MapErr
,MissingKeyErr
,PredicateErrs
[Any
],SetErrs
,TypeErr
,ValidationErrBase
,UnionErrs
]