structtype

structtype is a fast data structure validation and JSON serialization library for Python. It features:

  • A speedy Struct type for representing structured data. If you already use dataclasses or attrs, pydantic BaseModel, Structs should feel familiar.

  • 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.

  • Nearly zero-cost schema validation using familiar Python type annotations. In benchmarks structtype decodes and validates JSON faster than other libraries like pydantic.

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 keeping the conveniences of validation libraries like pydantic. For supported types, encoding/decoding a message with structtype is faster than alternative libraries; see the benchmarks for the full numbers.

Highlights

  • structtype is fast. It benchmarks as the fastest serialization library for Python, outperforming all other JSON libraries compared.

  • structtype is friendly. Through use of Python’s type annotations, messages are validated during deserialization in a declarative way. structtype also works well with other type-checking tooling like mypy and pyright, providing excellent editor integration.

  • structtype is correct. The JSON encoder/decoder is strictly compliant with the JSON specification, providing strong guarantees of compatibility.