ValidatedDC
Dataclass with data validation. Checks the value of its fields by their annotations.
Capabilities
ValidatedDC
is a regular Python dataclass.
- Support for standard types and custom Python classes.
- Support for some aliases from the
typing
module, namely: Any
, List
, Literal
, Optional
, Union
. These aliases can be embedded in each other. - When initializing an instance of a class, you can use the value of the field
dict
instead of the ValidatedDC
instance specified in the field annotation (useful, for example, when retrieving data via api). - Data validation occurs immediately after an instance is created, and can also be run by the
is_valid()
function at any time. - The
get_errors()
function will show the full traceback of errors in the fields, including errors of nested classes.
See detailed in the examples
folder.
Installation
pip install validated-dc
Python versions support
Versions 3.7
, 3.8
and 3.9
are currently supported.
To work with version python 3.7
you need to install:
pip install typing_extensions
Quick example
from dataclasses import dataclass
from typing import List, Union
from validated_dc import ValidatedDC, get_errors, is_valid
@dataclass
class Foo(ValidatedDC):
value: Union[int, List[int]]
@dataclass
class Bar(ValidatedDC):
foo: Union[Foo, List[Foo]]
foo = {'value': 1}
instance = Bar(foo=foo)
assert get_errors(instance) is None
assert instance == Bar(foo=Foo(value=1))
foo = {'value': [1, 2]}
instance = Bar(foo=foo)
assert get_errors(instance) is None
assert instance == Bar(foo=Foo(value=[1, 2]))
foo = [{'value': 1}, {'value': 2}]
instance = Bar(foo=foo)
assert get_errors(instance) is None
assert instance == Bar(foo=[Foo(value=1), Foo(value=2)])
foo = [{'value': [1, 2]}, {'value': [3, 4]}]
instance = Bar(foo=foo)
assert get_errors(instance) is None
assert instance == Bar(foo=[Foo(value=[1, 2]), Foo(value=[3, 4])])
foo = {'value': 'S'}
instance = Bar(foo=foo)
assert get_errors(instance)
assert instance == Bar(foo={'value': 'S'})
instance.foo['value'] = 1
assert is_valid(instance)
assert get_errors(instance) is None
assert instance == Bar(foo=Foo(value=1))
foo = [{'value': [1, 2]}, {'value': ['S', 4]}]
instance = Bar(foo=foo)
assert get_errors(instance)
assert instance == Bar(foo=[{'value': [1, 2]}, {'value': ['S', 4]}])
instance.foo[1]['value'][0] = 3
assert is_valid(instance)
assert get_errors(instance) is None
assert instance == Bar(foo=[Foo(value=[1, 2]), Foo(value=[3, 4])])
foo = {'value': 'S'}
instance = Bar(foo=foo)
print(get_errors(instance))