dataclass-native
Use Python dataclasses as a data description language.
Why do this? I'm glad you asked! This approach solves several problems I've wrestled with when creating object models in Python which need to interact with native code implementations for performance reasons. The classic example is quant finance code. My main requirements are:
- Pythonic data classes, which interact nicely with pyright and other static checkers
- Ability to run the python code without code generation steps
- No-copy semantics when interacting with native code
Protobufs fail on points 1. and 2., produce hideous python and require you to distribute the protobuf definitions.
AVRO is a bit more friendly but generates its classes dynamically which fails point 1.
The approach of dataclass-native is to generate native classes - currently C++, with Rust to follow, whose storage the Python classes use directly. Native serialisation (msgpack, Arrow/Parquet) is planned.
Status: early. Schema introspection, C++ header generation and the native Python binding work. Serialisation works to msgpack and to Arrow, in Python and C++, and to Parquet through pyarrow. Rust is to come: see DESIGN.md.
Defining a schema
import datetime as dt
from collections.abc import Mapping
from dataclasses import dataclass
from enum import Enum, auto
from dataclass_native import DiscriminatedUnion, Int32, Shared, native
class Currency(Enum):
USD = auto()
EUR = auto()
@native
@dataclass(frozen=True)
class Money:
amount: float
currency: Currency = Currency.USD
@native(tag="party.v1") # Names the type when serialised
@dataclass(frozen=True)
class Party:
name: str
rating: Int32 = 0
@native
@dataclass(frozen=True)
class Cash:
money: Money
@native
@dataclass(frozen=True)
class Bond:
isin: str
@native
@dataclass(frozen=True)
class Trade:
id: int
# Two structs: needs a tag when serialised
instrument: DiscriminatedUnion[Cash, Bond]
# Shared, not copied; serialised by reference
counterparty: Shared[Party]
tags: tuple[str, ...] = ()
limits: Mapping[Currency, float] | None = None
executed: dt.datetime | None = None
Classes are best frozen. One which is not may have its fields set, and what holds it holds that object, not a copy
of it, as in Python: order.customer.name = "Ann" changes the customer. Its containers are still immutable, so are
set whole.
Containers are tuple[T, ...], tuple[A, B], frozenset[T] and Mapping[K, V].
Beyond the builtin types and those of datetime, a field may be a UUID, a NaiveDatetime (a datetime must have a
timezone), and a Decimal of a given number of decimal places: Annotated[Decimal, DecimalPlaces(2)].
A field may also be a numpy array of numbers: points: Vector[np.float64] or surface: Matrix[np.float64], from
dataclass_native.arrays, or of more dimensions as numpy annotates it:
np.ndarray[tuple[int, int, int], np.dtype[np.uint8]]. Unlike a tuple, it is not copied when read: the array you
get is a read-only view of the numbers in the C++ struct, or one you may write to if its class is not frozen. This
needs numpy: install dataclass-native[numpy].
A class may also be a pydantic dataclass (pydantic.dataclasses.dataclass(frozen=True)), to validate and convert
what its objects are made from. pydantic's BaseModel is not supported, it does unfortunate things like setting __dict__ directly on objects and has complicated (and rather ugly) code in __setattr__ etc, which interferes with the descriptors. BaseModel and descriptors are generally unhappy bedfellows.
Generating C++
dataclass-native generate cpp --package my_schemas --out generated/include
dataclass-native include-dir # dataclass_native's own headers, which the generated headers include
This writes a header per module (my_schemas/trades.hpp, namespace my_schemas::trades) of plain C++20 structs,
with no dependency on Python:
struct Trade
{
std::int64_t id{};
dataclass_native::DiscriminatedUnion<Cash, Bond> instrument{};
dataclass_native::Shared<Party> counterparty{};
std::vector<std::string> tags = std::vector<std::string>{};
std::optional<std::map<Currency, double>> limits = std::nullopt;
std::optional<dataclass_native::DateTime> executed = std::nullopt;
bool operator==(const Trade&) const = default;
};
Unchanged files are untouched, so builds don't rerun needlessly.
Storing Python objects in the structs
Each schema module my_schemas.trades has an extension module, my_schemas._trades_native, generated by
dataclass-native generate nanobind and built with nanobind. With CMake:
cmake_minimum_required(VERSION 3.25)
project(my_schemas LANGUAGES CXX)
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
execute_process(
COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
find_package(nanobind CONFIG REQUIRED)
execute_process(
COMMAND "${Python_EXECUTABLE}" -m dataclass_native cmake-dir
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE dataclass_native_ROOT)
find_package(dataclass_native CONFIG REQUIRED)
# Generates the C++ and adds an extension for each schema module of the package, installed alongside it
dataclass_native_add_extensions(PACKAGES my_schemas PYTHONPATH "${CMAKE_SOURCE_DIR}/src")
The extensions are installed to their packages' directories, as a build backend such as scikit-build-core expects.
To use them in place instead, add LIBRARY_DIRECTORY "${CMAKE_SOURCE_DIR}/src".
A class is then bound to its struct when first instantiated. Nothing else changes: it is still the dataclass you
wrote, to type checkers and to dataclasses.
party = Party("Acme")
trade = Trade(id=1, instrument=Cash(Money(100.0)), counterparty=party)
trade.instrument.money.amount # 100.0, read from the C++ struct
trade.counterparty is party # True: shared, not copied
vars(trade) # {'__native__': <my_schemas._trades_native.Trade object>}
Trade(id="1", ...) # TypeError: Trade.id cannot be '1'
Calling C++ functions
A C++ function of the structs is called from Python as a function of the dataclasses. Bind it with nanobind, in an extension of your own:
#include "dataclass_native/python.hpp"
#include "my_schemas/trades.hpp"
int rating(const my_schemas::trades::Trade& trade); // Plain C++, knowing nothing of Python
NB_MODULE(_risk, m)
{
m.def("rating", &rating);
}
and declare it in Python, naming that extension:
from dataclass_native import native_function
@native_function("._risk") # my_schemas._risk: relative to this module's package
def rating(trade: Trade) -> int:
return trade.counterparty.rating
rating(trade) then calls the C++ function with the struct in which the trade's fields are stored, without copying
it. A struct which C++ returns likewise becomes the object of the return annotation. The body is the function's
Python implementation, which is what runs in pure mode. See examples/functions.
Serialising
from dataclass_native import from_msgpack, to_msgpack
data = to_msgpack(trade) # bytes
from_msgpack(Trade, data) == trade # True
The bytes are msgpack, in the format of WIRE_FORMAT.md. An object held by Shared fields is
written once, so the party two trades share is still one object when they are read back.
An object stored natively is written and read by C++, and a plain one, as in pure mode, by Python. Both write
the same bytes, so what one writes the other reads. C++ of your own does the same, with no dependency on Python:
#include "dataclass_native/msgpack.hpp"
dataclass_native::Bytes data = dataclass_native::msgpack::to_msgpack(trade);
auto read = dataclass_native::msgpack::from_msgpack<Trade>(data);
JSON
from dataclass_native import from_json, to_json
data = to_json(trade) # bytes, of UTF-8
from_json(Trade, data) == trade # True
In the format of JSON_FORMAT.md, which pydantic's TypeAdapter of the same class reads, and
writes what this reads. An object held by Shared fields is written wherever it is held, so is no longer shared
when read back. As with msgpack, objects stored natively are written and read by C++, and plain ones by Python,
character for character the same. In C++ of your own:
#include "dataclass_native/json.hpp"
std::string data = dataclass_native::json::to_json(trade);
auto read = dataclass_native::json::from_json<Trade>(data);
Arrow and Parquet
from dataclass_native import from_parquet, to_arrow, to_parquet
tables = to_arrow(trades) # tables.root is a pyarrow.Table, with a row for each trade
# trades/root.parquet, and a file for each class the trades share
to_parquet(trades, "trades")
from_parquet(Trade, "trades") == trades # True
This needs pyarrow: install dataclass-native[arrow]. Each field is a column, and an object held by Shared
fields is a row of its class's own table, which those fields refer to by row, as a foreign key does. The layout is
in ARROW_FORMAT.md. A class which holds itself, such as a tree, cannot be written.
As with msgpack, objects stored natively are held and read by C++, and plain ones by Python, in the same layout. C++ of your own builds the tables with no Arrow library, as the structs of Arrow's C data interface, which any Arrow library imports without copying:
#include "dataclass_native/arrow.hpp"
auto tables = dataclass_native::arrow::to_arrow<Trade>(std::span<const Trade>(trades));
// tables.root.schema and tables.root.array: an ArrowSchema and an ArrowArray
Parquet files are written from them, in C++, by an Arrow library which you link: the
parquet example does so with Arrow C++, writing and reading the files which to_parquet and
from_parquet do.
Modes
DATACLASS_NATIVE_MODE is one of:
strict(the default): fields are stored in the native structs, and a class whose binding is missing raises.mixed: asstrict, but a class whose binding is missing behaves as a plain dataclass.pure:@nativereturns every class unchanged, as a plain dataclass, for testing.
A @native_function follows them: strict raises if its native function is missing, mixed then calls its body, and
pure always calls its body.
A binding built from another version of its class raises in strict and mixed modes: build it again.
Examples
examples has projects to copy from: a schema stored natively and one with C++ functions, each built by scikit-build-core, and a C++ program which writes Parquet files with Arrow C++.
Development
uv sync
uv run pre-commit install # Then ruff and pyright run on committing
uv run pytest # Builds the extensions of tests/schemas, and the examples, with CMake in build/tests
CI runs the same hooks (uv run pre-commit run --all-files) and the tests, on Linux, macOS and Windows.
Metadata
Release files for dataclass-native 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dataclass_native-1.0.0.tar.gz | 246.7 kB | With provenance | Details for dataclass_native-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dataclass_native-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for dataclass_native-1.0.0-py3-none-any.whl |
Total release size: 360.9 kB
Release files / dataclass_native-1.0.0.tar.gz
| Download URL | dataclass_native-1.0.0.tar.gz |
|---|---|
| Size | 246.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4454ca794a5811145dfd078b7c87f87f67cbe5d1a5ef396d3dd7774979c0dd61
|
|
BLAKE2b-256 checksum How to use checksums |
372a0e2abc8c2ea52b2941b5425b75dd09a57f64af5e94534f491a48cbdde0e7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / dataclass_native-1.0.0-py3-none-any.whl
| Download URL | dataclass_native-1.0.0-py3-none-any.whl |
|---|---|
| Size | 114.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5deed502d8ab7bd192daa9fe5390f8628c99be8eb87af80d9432439e9dff6632
|
|
BLAKE2b-256 checksum How to use checksums |
67146d39f3458ebfea5a801ee676bd73390e0cb362e6ba80ae785e6453f49a8e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logSecurity for dataclass-native 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for dataclass_native-1.0.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.