structtype¶
structtype is a fast struct validation and JSON serialization library for
Python. It features:
🚀 High performance JSON encoder/decoder. Regularly benchmarks as the fastest option for Python.
🎉 Support for a wide variety of Python types. Additional types may be supported through extensions.
🔍 Zero-cost schema validation using familiar Python type annotations. In benchmarks
structtypedecodes and validates JSON faster than orjson can decode it alone.✨ A speedy Struct type for representing structured data. If you already use dataclasses or attrs, Structs should feel familiar. However, they’re 5-60x faster for common operations.
All of this is included in a lightweight library with no required dependencies.
Define your message schemas using standard Python type annotations.
>>> from structtype import Struct
>>> class User(Struct):
... """A new type describing a User"""
... name: str
... groups: set[str] = set()
... email: str | None = None
Encode and decode messages as JSON, with optional schema validation.
>>> alice = User("alice", groups={"admin", "engineering"})
>>> alice
User(name='alice', groups={"admin", "engineering"}, email=None)
>>> alice.struct_dump_json()
b'{"name":"alice","groups":["admin","engineering"],"email":null}'
>>> User.struct_validate_json(
... b'{"name":"alice","groups":["admin","engineering"],"email":null}'
... )
User(name='alice', groups={"admin", "engineering"}, email=None)
>>> User.struct_validate_json(b'{"name":"bob","groups":[123]}')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
structtype.ValidationError: Expected `str`, got `int` - at `$.groups[0]`
structtype is designed to be as performant as possible, while retaining some
of the nicities of validation libraries like pydantic. For supported types,
encoding/decoding a message with structtype can be ~10-80x faster than
alternative libraries.
Highlights¶
structtypeis fast. It benchmarks as the fastest serialization library for Python, outperforming all other JSON libraries compared.structtypeis friendly. Through use of Python’s type annotations, messages are validated during deserialization in a declarative way.structtypealso works well with other type-checking tooling like mypy and pyright, providing excellent editor integration.structtypeis flexible. It natively supports a wide range of Python builtin types. Support for additional types can also be added through extensions.structtypeis lightweight. It has no required dependencies, and the binary size is a fraction of that of comparable libraries.structtypeis correct. The JSON encoder/decoder is strictly compliant with the JSON specification, providing strong guarantees of compatibility.