Reference¶
Abstract¶
-
class
validx.py.
Validator
(alias=None, replace=False)[source]¶ Abstract Base Validator
Parameters: - alias (str) – if it specified,
the instance will be added into registry,
see
validx.py.instances.add()
. - replace (bool) – if it is
True
andalias
specified, the instance will be added into registry, replacing any existent validator with the same alias, seevalidx.py.instances.put()
. - **kw – concrete validator attributes.
-
__call__
(value, _Validator__context=None)[source]¶ Validate value.
This is an abstract method, and it should be implemented by descendant class.
-
static
load
(params, update=None, unset=None, **kw)[source]¶ Load validator.
>>> Validator.load({ ... "__class__": "Int", ... "min": 0, ... "max": 100, ... }) <Int(min=0, max=100)> >>> # Add into registry >>> some_int = Validator.load({ ... "__class__": "Int", ... "min": 0, ... "max": 100, ... "alias": "some_int", ... }) >>> some_int <Int(min=0, max=100)> >>> # Load from registry by alias >>> Validator.load({"__use__": "some_int"}) is some_int True >>> # Clone from registry by alias >>> Validator.load({ ... "__clone__": "some_int", ... "update": { ... "min": -100, ... }, ... }) <Int(min=-100, max=100)>
-
dump
()[source]¶ Dump validator.
>>> Int(min=0, max=100).dump() == { ... "__class__": "Int", ... "min": 0, ... "max": 100, ... } True
-
clone
(update=None, unset=None, **kw)[source]¶ Clone validator.
>>> some_enum = Int(options=[1, 2, 3]) >>> some_enum.clone( ... { ... "nullable": True, ... "options+": [4, 5], ... "options-": [1, 2], ... } ... ) == Int(nullable=True, options=[3, 4, 5]) True
In fact, the method is a shortcut for:
self.load(self.dump(), update, **kw)
- alias (str) – if it specified,
the instance will be added into registry,
see
Numbers¶
-
class
validx.py.
Int
(nullable=False, coerce=False, min=None, max=None, options=None, alias=None, replace=False)[source]¶ Integer Number Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - coerce (bool) – try to convert non-integer value to
int
. - min (int) – lower limit.
- max (int) – upper limit.
- options (iterable) – explicit enumeration of valid values.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, int)
andnot self.coerce
.
- if
- CoerceError – if
self.coerce
andint(value)
raises an exception. - MinValueError – if
value < self.min
. - MaxValueError – if
value > self.max
. - OptionsError – if
value not in self.options
.
Note: It implicitly converts
float
toint
, ifvalue.is_integer() is True
.- nullable (bool) – accept
-
class
validx.py.
Float
(nullable=False, coerce=False, nan=False, inf=False, min=None, max=None, alias=None, replace=False)[source]¶ Floating Point Number Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - coerce (bool) – try to convert non-float value to
float
. - nan (bool) – accept
Not-a-Number
as a valid value. - inf (bool) – accept
Infinity
as a valid value. - min (float) – lower limit.
- max (float) – upper limit.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, float)
andnot self.coerce
.
- if
- CoerceError – if
self.coerce
andfloat(value)
raises an exception. - NumberError –
- if
math.isnan(value)
andnot self.nan
; - if
math.isinf(value)
andnot self.inf
.
- if
- MinValueError – if
value < self.min
. - MaxValueError – if
value > self.max
.
Note: It always converts
int
tofloat
.- nullable (bool) – accept
-
class
validx.py.
Decimal
(nullable=False, coerce=False, precision=None, nan=False, inf=False, min=None, max=None, alias=None, replace=False)[source]¶ Fixed Point Number Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - coerce (bool) – try to convert non-decimal value to
decimal.Decimal
. - precision (int) – number of decimal places after point.
- nan (bool) – accept
Not-a-Number
as a valid value. - inf (bool) – accept
Infinity
as a valid value. - min (decimal.Decimal) – lower limit.
- max (decimal.Decimal) – upper limit.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, decimal.Decimal)
andnot self.coerce
.
- if
- CoerceError – if
self.coerce
anddecimal.Decimal(value)
raises an exception. - NumberError –
- if
value.is_nan()
andnot self.nan
; - if
value.is_infinite()
andnot self.inf
.
- if
- MinValueError – if
value < self.min
. - MaxValueError – if
value > self.max
.
Note: It always converts
int
andfloat
todecimal.Decimal
.- nullable (bool) – accept
Chars¶
-
class
validx.py.
Str
(nullable=False, coerce=False, dontstrip=False, normspace=False, encoding=None, minlen=None, maxlen=None, pattern=None, options=None, alias=None, replace=False)[source]¶ Unicode String Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - coerce (bool) – convert non-string value to
str
, use with caution (see notes below). - dontstrip (bool) – do not strip leading & trailing whitespace.
- normspace (bool) – normalize spaces, i.e. replace any space sequence by single space char.
- encoding (str) – try to decode
bytes
tostr
using specified encoding. - minlen (int) – lower length limit.
- maxlen (int) – upper length limit.
- pattern (str) – validate string using regular expression.
- options (iterable) – explicit enumeration of valid values.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, str)
.
- if
- StrDecodeError – if
value.decode(self.encoding)
raisesUnicodeDecodeError
. - MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
. - PatternMatchError – if
value
does not matchself.pattern
. - OptionsError – if
value not in self.options
.
Note: Since any Python object can be converted to a string, using
coerce
without other checks in fact validates nothing. It can be useful though to sanitize data from sources with automatic type inferring, where string data might be incorrectly interpreted as another type. For example, phone number asint
, version number asfloat
, etc.- nullable (bool) – accept
-
class
validx.py.
Bytes
(nullable=False, minlen=None, maxlen=None, alias=None, replace=False)[source]¶ Byte String Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - minlen (int) – lower length limit.
- maxlen (int) – upper length limit.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, bytes)
.
- if
- MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
.
- nullable (bool) – accept
Date and Time¶
-
class
validx.py.
Date
(nullable=False, unixts=False, format=None, parser=None, min=None, max=None, relmin=None, relmax=None, tz=None, alias=None, replace=False)[source]¶ Date Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - unixts (bool) – convert Unix timestamp (
int
orfloat
) todate
. - format (str) – try to parse
date
fromstr
usingdatetime.strptime(value, self.format).date()
. - parser (callable) – try to parse
date
fromstr
usingself.parser(value).date()
. - min (date) – absolute lower limit.
- max (date) – absolute upper limit.
- relmin (timedelta) – relative lower limit.
- relmax (timedelta) – relative upper limit.
- tz (tzinfo) – timezone, see notes below.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
isinstance(value, (int, float))
andnot self.unixts
; - if
isinstance(value, bool) and self.unixts
, becauseissubclass(bool, int) is True
, but it is very unlikelybool
could represent a valid timestamp; - if
not isinstance(value, date)
.
- if
- DatetimeParseError –
- if
datetime.strptime(value, self.format)
raisesValueError
; - if
self.parser(value)
raisesValueError
.
- if
- MinValueError –
- if
value < self.min
; - if
value < date.today() + self.relmin
; - if
self.unixts
and value lesser than the minimal supported timestamp.
- if
- MaxValueError –
- if
value > self.max
; - if
value > date.today() + self.relmax
; - if
self.unixts
and value greater than the maximal supported timestamp.
- if
Note: Relative limits are calculated adding deltas to current date, use negative
relmin/relmax
to specify date in the past.Note: It implicitly converts
datetime
todate
. If timezone is specified anddatetime
object is timezone-aware, it will be arranged to specified timezone first.Note: If timezone is specified, it will be used in conversion from Unix timestamp. In fact, it will create
datetime
object in UTC, usingdatetime.fromtimestamp(value, UTC)
. And then arrange it to specified timezone, and extract date part. It also will be used in the same way to gettoday
value forrelmin/relmax
checks, i.e.datetime.now(UTC).astimezone(self.tz).date()
.- nullable (bool) – accept
-
class
validx.py.
Time
(nullable=False, format=None, parser=None, min=None, max=None, alias=None, replace=False)[source]¶ Time Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - format (str) – try to parse
time
fromstr
usingdatetime.strptime(value, self.format).time()
. - parser (callable) – try to parse
time
fromstr
usingself.parser(value).time()
. - min (time) – lower limit.
- max (time) – upper limit.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, time)
.
- if
- DatetimeParseError –
- if
datetime.strptime(value, self.format)
raisesValueError
; - if
self.parser(value)
raisesValueError
.
- if
- MinValueError – if
value < self.min
. - MaxValueError – if
value > self.max
.
- nullable (bool) – accept
-
class
validx.py.
Datetime
(nullable=False, unixts=False, format=None, parser=None, min=None, max=None, relmin=None, relmax=None, default_time=None, tz=None, alias=None, replace=False)[source]¶ Date & Time Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - unixts (bool) – convert Unix timestamp (
int
orfloat
) todatetime
. - format (str) – try to parse
datetime
fromstr
usingdatetime.strptime(value, self.format)
. - parser (callable) – try to parse
datetime
fromstr
usingself.parser(value)
. - min (datetime) – absolute lower limit.
- max (datetime) – absolute upper limit.
- relmin (timedelta) – relative lower limit.
- relmax (timedelta) – relative upper limit.
- default_time (time) – is used to implicitly convert
date
todatetime
usingdatetime.combine(value, self.default_time or time(tzinfo=self.tz))
. - tz (tzinfo) – timezone.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
isinstance(value, (int, float))
andnot self.unixts
; - if
isinstance(value, bool) and self.unixts
, becauseissubclass(bool, int) is True
, but it is very unlikelybool
could represent a valid timestamp; - if
not isinstance(value, datetime)
.
- if
- DatetimeParseError –
- if
datetime.strptime(value, self.format)
raisesValueError
; - if
self.parser(value)
raisesValueError
.
- if
- DatetimeTypeError –
- if
self.tz is None and value.tzinfo is not None
; - if
self.tz is not None and value.tzinfo is None
;
- if
- MinValueError –
- if
value < self.min
; - if
self.tz is None and value < datetime.now() + self.relmin
. - if
self.tz is not None and value < datetime.now(UTC).astimezone(self.tz) + self.relmin
; - if
self.unixts
and value lesser than the minimal supported timestamp.
- if
- MaxValueError –
- if
value > self.max
; - if
self.tz is None and value > datetime.now() + self.relmax
. - if
self.tz is not None and value > datetime.now(UTC).astimezone(self.tz) + self.relmax
; - if
self.unixts
and value greater than the maximal supported timestamp.
- if
- nullable (bool) – accept
Boolean¶
-
class
validx.py.
Bool
(nullable=False, coerce_str=False, coerce_int=False, alias=None, replace=False)[source]¶ Boolean Validator
Parameters: - nullable (bool) – accept
None
as a valid value. - coerce_str (bool) –
- accept values
["1", "true", "yes", "y", "on"]
asTrue
; - accept values
["0", "false", "no", "n", "off"]
asFalse
.
- accept values
- coerce_int (bool) – accept
int
as valid value.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
isinstance(value, str)
andnot self.coerce_str
; - if
isinstance(value, int)
andnot self.coerce_int
; - if
not isinstance(value, bool)
.
- if
- OptionsError – when string value is not valid name, see
coerce_str
.
- nullable (bool) – accept
Containers¶
-
class
validx.py.
List
(item, nullable=False, sort=None, sort_key=None, minlen=None, maxlen=None, unique=False, alias=None, replace=False)[source]¶ List Validator
Parameters: - item (Validator) – validator for list items.
- nullable (bool) – accept
None
as a valid value. - sort (int) –
1
for ascending,-1
for descending. - sort_key (callable) – function to extract a comparison key.
- minlen (int) – lower length limit.
- maxlen (int) – upper length limit.
- unique (bool) – drop duplicate items.
Raises: - InvalidTypeError – if
not isinstance(value, Iterable)
. - MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
. - SchemaError – with all errors, raised by item validator.
-
class
validx.py.
Set
(item, nullable=False, minlen=None, maxlen=None, alias=None, replace=False)[source]¶ Set Validator
Parameters: - item (Validator) – validator for set items.
- nullable (bool) – accept
None
as a valid value. - minlen (int) – lower length limit.
- maxlen (int) – upper length limit.
Raises: - InvalidTypeError – if
not isinstance(value, Iterable)
. - MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
. - SchemaError – with all errors, raised by item validator.
-
class
validx.py.
Tuple
(*items_, items=None, nullable=False, alias=None, replace=False)[source]¶ Tuple Validator
Parameters: - *items (Validator) – validators for tuple members.
- nullable (bool) – accept
None
as a valid value.
Raises: - InvalidTypeError – if
not isinstance(value, (list, tuple))
. - TupleLengthError – if
len(value) != len(self.items)
. - SchemaError – with all errors, raised by member validators.
-
class
validx.py.
Dict
(schema=None, nullable=False, minlen=None, maxlen=None, extra=None, defaults=None, optional=None, dispose=None, multikeys=None, alias=None, replace=False)[source]¶ Dictionary Validator
Parameters: - schema (dict) – schema validator in format
{<key>: <validator>}
. - nullable (bool) – accept
None
as a valid value. - minlen (int) – lower length limit.
- maxlen (int) – upper length limit.
- extra (tuple) – validators for extra keys and values in format
(<key_validator>, <value_validator>)
, it is used for keys are not presented inschema
. - defaults (dict) – default values for missing keys.
- optional (list or tuple) – list of optional keys.
- dispose (list or tuple) – list of keys that have to be silently removed.
- multikeys (list or tuple) – list of keys that have to be treated as lists of values,
if input value is a
MultiDict
(see notes below), i.e. value of these keys will be extracted usingval = value.getall(key)
orval = value.getlist(key)
.
Raises: - InvalidTypeError – if
not isinstance(value, collections.abc.Mapping)
. - MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
. - SchemaError – with all errors, raised by schema validators, extra validators, and missing required and forbidden extra keys.
Note: on error raised by
extra
validators, context markervalidx.exc.Extra
will be used to indicate, which part of key/value pair is failed.It has been tested against the following implementations of
MultiDict
:However, it should work fine for other implementations, if the implementation is subclass of
collections.abc.Mapping
, and providesgetall()
orgetlist()
methods.- schema (dict) – schema validator in format
Pipelines¶
-
class
validx.py.
AllOf
(*steps_, steps=None, alias=None, replace=False)[source]¶ AND-style Pipeline Validator
All steps must be succeeded. The last step returns result.
Parameters: *steps (Validator) – nested validators. Raises: ValidationError – raised by the first failed step. Note: it uses validx.exc.Step
marker to indicate, which step is failed.
-
class
validx.py.
OneOf
(*steps_, steps=None, alias=None, replace=False)[source]¶ OR-style Pipeline Validator
The first succeeded step returns result.
Parameters: *steps (Validator) – nested validators. Raises: SchemaError – if all steps are failed, so it contains all errors, raised by each step. Note: it uses validx.exc.Step
marker to indicate, which step is failed.
Special¶
-
class
validx.py.
LazyRef
(use, maxdepth=None, alias=None, replace=False)[source]¶ Lazy Referenced Validator
It is useful to build validators for recursive structures.
>>> schema = Dict( ... { ... "foo": Int(), ... "bar": LazyRef("schema", maxdepth=1), ... }, ... optional=("foo", "bar"), ... minlen=1, ... alias="schema", ... ) >>> schema({"foo": 1}) {'foo': 1} >>> schema({"bar": {"foo": 1}}) {'bar': {'foo': 1}} >>> schema({"bar": {"bar": {"foo": 1}}}) Traceback (most recent call last): ... validx.exc.errors.SchemaError: <SchemaError(errors=[ <bar.bar: RecursionMaxDepthError(expected=1, actual=2)> ])>
Parameters: - use (str) – alias of referenced validator.
- maxdepth (int) – maximum recursion depth.
Raises: RecursionMaxDepthError – if
self.maxdepth is not None
and current recursion depth exceeds the limit.
-
class
validx.py.
Type
(tp, nullable=False, coerce=False, min=None, max=None, minlen=None, maxlen=None, options=None, alias=None, replace=False)[source]¶ Custom Type Validator
Parameters: - tp (type) – valid value type.
- nullable (bool) – accept
None
as a valid value. - coerce (bool) – try to convert value to
tp
. - min (tp) – lower limit, makes sense only if
tp
provides comparison methods. - max (tp) – upper limit, makes sense only if
tp
provides comparison methods. - minlen (int) – lower length limit, makes sense only if
tp
provides__len__()
method. - maxlen (int) – upper length limit, makes sense only if
tp
provides__len__()
method. - options (iterable) – explicit enumeration of valid values.
Raises: - InvalidTypeError –
- if
value is None
andnot self.nullable
; - if
not isinstance(value, self.tp)
andnot self.coerce
.
- if
- CoerceError – if
self.coerce
andtp(value)
raises an exception. - MinValueError – if
value < self.min
. - MaxValueError – if
value > self.max
. - MinLengthError – if
len(value) < self.minlen
. - MaxLengthError – if
len(value) > self.maxlen
. - OptionsError – if
value not in self.options
.
-
class
validx.py.
Const
(value, alias=None, replace=False)[source]¶ Constant Validator
It only accepts single predefined value.
Parameters: value – expected valid value. Raises: OptionsError – if value != self.value
.
Class Registry¶
-
validx.py.classes.
add
(class_)[source]¶ Add validator class into the registry
Parameters: class (Validator) – class to register. Raises: AssertionError – if there is a class in the registry with the same name, i.e. class_.__name__
.Returns: unmodified passed class, so the function can be used as a decorator.
Instance Registry¶
-
validx.py.instances.
add
(alias, instance)[source]¶ Add validator into the registry
Parameters: - alias (str) – alias of the validator.
- instance (Validator) – instance of the validator.
Raises: AssertionError – if there is an instance in the registry with the same alias.
Returns: unmodified instance of passed validator.
-
validx.py.instances.
put
(alias, instance)[source]¶ Put validator into the registry
The function silently replaces any instance with the same alias.
Parameters: - alias (str) – alias of the validator.
- instance (Validator) – instance of the validator.
Returns: unmodified instance of passed validator.
Errors¶
The class hierarchy for exceptions is:
ValueError
(built-in)
-
class
validx.exc.
ValidationError
(context=None, *args, **kw)[source]¶ Validation Error Base Class
Parameters: - context (deque) – error context,
empty
deque
by default. - **kw – concrete error attributes.
Since validators try to process as much as possible, they can raise multiple errors (wrapped by
validx.exc.SchemaError
). To unify handling of such errors, each validation error providesSequence
interface. It means, you can iterate them, get their length, get nested errors by index, and sort nested errors by context.Error context is a full path, that indicates where the error occurred. It contains mapping keys, sequence indexes, and special markers (see
validx.exc.Extra
andvalidx.exc.Step
).>>> from validx import exc, Dict, List, Int >>> schema = Dict({"foo": List(Int(max=100))}) >>> try: ... schema({"foo": [1, 2, 200, 250], "bar": None}) ... except exc.ValidationError as e: ... error = e >>> error.sort() >>> error <SchemaError(errors=[ <bar: ForbiddenKeyError()>, <foo.2: MaxValueError(expected=100, actual=200)>, <foo.3: MaxValueError(expected=100, actual=250)> ])> >>> len(error) 3 >>> error[1] <foo.2: MaxValueError(expected=100, actual=200)> >>> error[1].context deque(['foo', 2]) >>> error[1].format_context() 'foo.2' >>> error[1].format_error() 'MaxValueError(expected=100, actual=200)' >>> error.sort(reverse=True) >>> error <SchemaError(errors=[ <foo.3: MaxValueError(expected=100, actual=250)>, <foo.2: MaxValueError(expected=100, actual=200)>, <bar: ForbiddenKeyError()> ])>
-
add_context
(node)[source]¶ Add error context
Parameters: node – key or index of member, where error is raised. Returns: the error itself, so that the method is suitable for chaining. Example:
>>> from validx.exc import ValidationError >>> e = ValidationError() >>> e <ValidationError()> >>> e.context deque([]) >>> e.add_context("foo") <foo: ValidationError()> >>> e.context deque(['foo'])
- context (deque) – error context,
empty
-
class
validx.exc.
ConditionError
(context=None, *args, **kw)[source]¶ Base Class for Condition Errors
It has a couple of attributes
expected
andactual
, that gives info of what happens and why the error is raised.See derived classes for details.
-
class
validx.exc.
InvalidTypeError
(context=None, *args, **kw)[source]¶ Invalid Type Error
Parameters: - expected (type or tuple) – expected type (types).
- actual (type) – actual type of value.
-
class
validx.exc.
CoerceError
(context=None, *args, **kw)[source]¶ Coerce Error
Parameters: - expected (type) – expected type.
- actual – actual value.
-
class
validx.exc.
OptionsError
(context=None, *args, **kw)[source]¶ Options Error
Parameters: - expected (list or tuple) – list of valid values.
- actual – actual value.
-
class
validx.exc.
MinValueError
(context=None, *args, **kw)[source]¶ Minimum Value Error
Parameters: - expected – minimal allowed value.
- actual – actual value.
-
class
validx.exc.
MaxValueError
(context=None, *args, **kw)[source]¶ Maximum Value Error
Parameters: - expected – maximal allowed value.
- actual – actual value.
-
class
validx.exc.
NumberError
(context=None, *args, **kw)[source]¶ Number Error
Parameters: - expected (str) –
"number"
on test forNot-a-Number
;"finite"
on test forInfinity
.
- actual (float or decimal.Decimal) – actual value.
- expected (str) –
-
class
validx.exc.
StrDecodeError
(context=None, *args, **kw)[source]¶ String Decode Error
Parameters: - expected (str) – encoding name.
- actual (bytes) – actual byte-string value.
-
class
validx.exc.
MinLengthError
(context=None, *args, **kw)[source]¶ Minimum Length Error
Parameters: - expected (int) – minimal allowed length.
- actual (int) – actual value length.
-
class
validx.exc.
MaxLengthError
(context=None, *args, **kw)[source]¶ Maximum Length Error
Parameters: - expected (int) – maximal allowed length.
- actual (int) – actual value length.
-
class
validx.exc.
TupleLengthError
(context=None, *args, **kw)[source]¶ Tuple Length Error
Parameters: - expected (int) – tuple length.
- actual (int) – actual value length.
-
class
validx.exc.
PatternMatchError
(context=None, *args, **kw)[source]¶ Pattern Match Error
Parameters: - expected (str) – pattern, i.e. regular expression.
- actual (str) – actual value.
-
class
validx.exc.
DatetimeParseError
(context=None, *args, **kw)[source]¶ Date & Time Parse Error
Parameters: - expected (str) – format.
- actual (str) – actual value.
-
class
validx.exc.
DatetimeTypeError
(context=None, *args, **kw)[source]¶ Date & Time Type Error
Parameters: - expected (str) – expected type of datetime: “naive” or “tzaware”.
- actual (datetime) – actual value.
-
class
validx.exc.
RecursionMaxDepthError
(context=None, *args, **kw)[source]¶ Recursion Maximum Depth Error
Parameters: - expected (int) – maximal allowed depth.
- actual (int) – actual recursion depth.
Context Markers¶
-
class
validx.exc.
Extra
(name)[source]¶ Extra Key Context Marker
It is a special context marker, that is used by mapping validators to indicate, which part of extra key/value pair is failed.
There are two constants in the module:
EXTRA_KEY
indicates that key validation is failed;EXTRA_VALUE
indicates that value validation is failed.
It has special representation, to be easily distinguished from other string keys.
Parameters: name (str) – name of pair part, i.e. KEY
orVALUE
.>>> from validx import exc, Dict, Str >>> schema = Dict(extra=(Str(maxlen=2), Str(maxlen=4))) >>> try: ... schema({"xy": "abc", "xyz": "abcde"}) ... except exc.ValidationError as e: ... error = e >>> error <SchemaError(errors=[ <xyz.@KEY: MaxLengthError(expected=2, actual=3)>, <xyz.@VALUE: MaxLengthError(expected=4, actual=5)> ])> >>> repr(error[0].context[1]) '@KEY' >>> error[0].context[1].name 'KEY' >>> error[0].context[1] is exc.EXTRA_KEY True >>> error[1].context[1] is exc.EXTRA_VALUE True
-
class
validx.exc.
Step
(num)[source]¶ Step Number Context Marker
It is a special context marker, that is used by pipeline validators to indicate, which validation step is failed. It has special representation, to be easily distinguished from sequence indexes.
Parameters: num (int) – number of failed step. >>> from validx import exc, OneOf, Int >>> schema = OneOf(Int(min=0, max=10), Int(min=90, max=100)) >>> try: ... schema(50) ... except exc.ValidationError as e: ... error = e >>> error <SchemaError(errors=[ <#0: MaxValueError(expected=10, actual=50)>, <#1: MinValueError(expected=90, actual=50)> ])> >>> repr(error[0].context[0]) '#0' >>> error[0].context[0].num 0 >>> isinstance(error[0].context[0], exc.Step) True
Error Formatter¶
-
class
validx.exc.
Formatter
(templates)[source]¶ Error Formatter
Parameters: templates (dict) – templates that will be used to format errors. Each key of
templates
should be a subclass ofvalidx.exc.ValidationError
.Each value of
templates
should be a string, i.e. simple template, or list of conditional templates.Conditional template is a tuple
(predicate, string)
. Wherepredicate
is a callable, that acceptsvalidx.exc.ValidationError
and returns boolean value. When the predicate evaluates toTrue
, its corresponding string will be used as a template.Last value of list of conditional templates can be a string, i.e. default simple template.
See
format_error
object, defined within the module, as an example.-
__call__
(error)[source]¶ Format Error
Parameters: error (ValidationError) – error to format. Returns: list of context/message pairs: [(str, str), ...]
.
-