Coder Social home page Coder Social logo

validated_dc's Introduction

ValidatedDC

PyPI version Build Status Coverage Status Language grade: Python Total alerts PyPI - Python Version

Dataclass with data validation. Checks the value of its fields by their annotations.

Capabilities

ValidatedDC is a regular Python dataclass.

  1. Support for standard types and custom Python classes.
  2. Support for some aliases from the typing module, namely: Any, List, Literal, Optional, Union. These aliases can be embedded in each other.
  3. 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).
  4. Data validation occurs immediately after an instance is created, and can also be run by the is_valid() function at any time.
  5. 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


# Some combinations of List and Union

@dataclass
class Foo(ValidatedDC):
    value: Union[int, List[int]]


@dataclass
class Bar(ValidatedDC):
    foo: Union[Foo, List[Foo]]


# --- Valid input ---

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])])


# --- Invalid input ---

foo = {'value': 'S'}
instance = Bar(foo=foo)
assert get_errors(instance)
assert instance == Bar(foo={'value': 'S'})
# fix
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]}])
# fix
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])])


# --- get_errors() ---

foo = {'value': 'S'}
instance = Bar(foo=foo)
print(get_errors(instance))
# {
#   'foo': [
#       # An unsuccessful attempt to use the dictionary to create a Foo instance
#       InstanceValidationError(
#           value_repr="{'value': 'S'}",
#           value_type=<class 'dict'>,
#           annotation=<class '__main__.Foo'>,
#           exception=None,
#           errors={
#               'value': [
#                   BasicValidationError(  # because the str isn't an int
#                       value_repr='S', value_type=<class 'str'>,
#                       annotation=<class 'int'>, exception=None
#                   ),
#                   BasicValidationError(  # and the str is not a list of int
#                       value_repr='S', value_type=<class 'str'>,
#                       annotation=typing.List[int], exception=None
#                   )
#               ]
#           }
#       ),
#       BasicValidationError(  # the dict is not a list of Foo
#           value_repr="{'value': 'S'}",
#           value_type=<class 'dict'>,
#           annotation=typing.List[__main__.Foo],
#           exception=None
#       )
#   ]
# }

validated_dc's People

Contributors

evgeniyburdin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

ejmvar

validated_dc's Issues

Support for type hinting generics In standard collections

Since Python 3.9, you can specify built-in types in generics, instead of duplicates from the typing module. For example typing.List and the built-in list. Now this library can only work with duplicates from typing.

@dataclass
class Data(ValidatedDC):
    ints: list[int]

Data([1]).get_errors()  # {'ints': [BasicValidationError(value_repr='[1]', value_type=<class 'list'>, annotation=list[int],
                        # exception=TypeError('isinstance() argument 2 cannot be a parameterized generic'))]}

Support for other built-in collections

Are you planning to add support for set, tuple, dict, etc. ?
Like this

@dataclasses.dataclass
class Data(ValidatedDC):
    ints: Set[int]
    strs: Tuple[str]
    map: Dict[str, int]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.