Trafaret
Trafaret is a rigid and powerful Python library for validation and parsing data structures. It provides a simple yet expressive way to define data schemas, perform checks, and convert data according to defined rules, offering clear error reporting. It's currently at version 2.1.1 and is actively maintained.
Warnings
- breaking The `String` trafaret's `regex` parameter was removed in 2.x. Users should now use `t.Regexp` or `t.RegexpRaw` for regular expression validation.
- breaking The `converters` and `convert=False` arguments for trafarets were removed in 2.x. Custom conversions should now use the `&` operator to chain functions or other trafarets.
- breaking Trafaret instances are no longer mutable in 2.x. Operations that previously modified a trafaret in place (e.g., `Dict.allow_extra()`, `Dict.make_optional()`) now return a new trafaret instance.
- deprecated The `StrBool` trafaret was renamed to `ToBool` in 2.x for clarity and consistency with other explicit conversion trafarets like `ToInt` and `ToFloat`.
- gotcha When using `trafaret.constructor.construct` in versions 2.0.2 and later, native Python `int` and `float` types passed as schema values will now automatically use `t.ToInt` and `t.ToFloat` respectively, implying conversion behavior. Earlier versions might have just validated the type.
Install
-
pip install trafaret
Imports
- trafaret
import trafaret as t
- DataError
from trafaret import DataError
- construct
from trafaret.constructor import construct
- Key
from trafaret.keys import Key
Quickstart
import datetime
import trafaret as t
# Define a trafaret for a date dictionary
date_validator = t.Dict(
year=t.Int,
month=t.Int(gte=1, lte=12),
day=t.Int(gte=1, lte=31)
) & (lambda d: datetime.datetime(**d))
# Valid data
valid_data = {'year': 2024, 'month': 4, 'day': 12}
try:
checked_date = date_validator.check(valid_data)
print(f"Valid date: {checked_date}")
except t.DataError as e:
print(f"Validation failed for valid data: {e.as_dict()}")
# Invalid data (missing day)
invalid_data = {'year': 2024, 'month': 4}
try:
date_validator.check(invalid_data)
except t.DataError as e:
print(f"Validation failed for invalid data: {e.as_dict()}")
# Invalid data (incorrect month)
invalid_month_data = {'year': 2024, 'month': 13, 'day': 1}
try:
date_validator.check(invalid_month_data)
except t.DataError as e:
print(f"Validation failed for incorrect month: {e.as_dict()}")