Runtime validators for attrs
pip install attrs-strictattrs runtime validation
attrs-strict is a Python package which contains runtime validation for
attrs data classes based on the types existing in the typing module.
Rationale
The purpose of the library is to provide runtime validation for attributes specified in
attrs data classes. The types supported are all the builtin types and most of the
ones defined in the typing library. For Python 2, the typing module is available through the backport found
here.
Quick Start
Type enforcement is based on the type attribute set on any field specified in an attrs dataclass. If the type
argument is not specified, no validation takes place.
pip install attrs-strict
from typing import List
import attr
from attrs_strict import type_validator
@attr.s
class SomeClass(object):
list_of_numbers = attr.ib(validator=type_validator(), type=List[int])
sc = SomeClass([1, 2, 3, 4])
print(sc)
SomeClass(list_of_numbers=[1, 2, 3, 4])
try:
SomeClass([1, 2, 3, "four"])
except ValueError as exception:
print(repr(exception))
SomeClass(list_of_numbers=[1, 2, 3, 4])
<list_of_numbers must be typing.List[int] (got four that is a <class 'str'>) in [1, 2, 3, 'four']>
Nested type exceptions are validated accordingly, and a backtrace to the initial container is maintained to ease with debugging. This means that if an exception occurs because a nested element doesn't have the correct type, the representation of the exception will contain the path to the specific element that caused the exception.