Registry / serialization / trafaret

trafaret

JSON →
library2.1.1pypypi✓ verified 24d ago

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 trafaret
INSTALL
IMPORT
SIG · TRAFARET
T
trafaret
serializationpythonv2.1.1
Install
1.6s avg
Import
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 18MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.000s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

trafaret
import trafaret as t
DataError
from trafaret import DataError
construct
from trafaret.constructor import construct
Key
from trafaret.keys import Key
t.Key
While t.Key works, explicit import from trafaret.keys is often clearer for specialized key handling.

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.

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()}")
Debug
Known issues
breakingThe `String` trafaret's `regex` parameter was removed in 2.x. Users should now use `t.Regexp` or `t.RegexpRaw` for regular expression validation.
fix
Replace `t.String(regex='...')` with `t.Regexp('...')` or `t.RegexpRaw('...')`.
affects: 1.x.x to 2.x.x
breakingThe `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.
fix
Refactor conversion logic to use the `&` operator, e.g., `t.Int & str` instead of `t.Int(converter=str)`.
affects: 1.x.x to 2.x.x
breakingTrafaret 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.
fix
Assign the result of such operations back to the trafaret variable, e.g., `my_trafaret = my_trafaret.allow_extra('new_key')`.
affects: 1.x.x to 2.x.x
deprecatedThe `StrBool` trafaret was renamed to `ToBool` in 2.x for clarity and consistency with other explicit conversion trafarets like `ToInt` and `ToFloat`.
fix
Update all instances of `t.StrBool` to `t.ToBool`.
affects: 1.x.x to 2.x.x
gotchaWhen 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.
fix
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.
affects: >=2.0.2
Errors
Common errors & fixes
Key 'some_field' is required
The input data is missing a key that is defined as required in the Trafaret schema.
fix
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`.
value is not 'int'
The input data provided for a field does not match the expected Python type (e.g., an integer) specified in the Trafaret schema.
fix
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).
N: value is not 'expected_type'
An item at the specified index (N) within a list or sequence does not conform to the expected type defined in the Trafaret schema for list elements.
fix
Modify the item at the given index N in the input list to match the type specified in the Trafaret schema for list elements.
specific_field: field is not allowed
The input data contains a key (`specific_field`) that is not explicitly defined in the Trafaret `Dict` schema, and `allow_extra` is not set to `True`.
fix
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.
Upgrade
Version history
2.1.1latest on PyPI · released Apr 1, 2022
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
OpenAI (training)
1
Resources
trafaret — pip install trafaret · libregistry