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.
pip install trafaretVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a Trafaret for a dictionary representing a date, including integer range validation for month and day. It also shows how to chain a converter function using the `&` operator to transform the validated dictionary into a `datetime.datetime` object. Error handling with `t.DataError` and `as_dict()` is also illustrated.
Replace `t.String(regex='...')` with `t.Regexp('...')` or `t.RegexpRaw('...')`.Refactor conversion logic to use the `&` operator, e.g., `t.Int & str` instead of `t.Int(converter=str)`.
Assign the result of such operations back to the trafaret variable, e.g., `my_trafaret = my_trafaret.allow_extra('new_key')`.Update all instances of `t.StrBool` to `t.ToBool`.
Be aware that `construct({'age': int})` will now convert '5' to 5. If strict type checking without conversion is desired, use `t.Type(int)` explicitly.Add the missing key to the input data with a valid value, or make the field optional in the schema using `trafaret.Optional` or `trafaret.Default`.
Ensure the input data's type matches the type defined in the Trafaret schema for that field (e.g., provide an integer for a `t.Int` field instead of a string).
Modify the item at the given index N in the input list to match the type specified in the Trafaret schema for list elements.
Remove the extra key from the input data or modify the Trafaret `Dict` schema by setting `allow_extra=True` if these fields should be permitted.
No dependency data recorded yet.