Skip to content

About

Python dataclasses as a data description language, using native classes for storage

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

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:

  1. Pythonic data classes, which interact nicely with pyright and other static checkers
  2. Idiomatic generated classes/structs in C++ and Rust, which integrate well with native code
  3. Ability to run the python code without code generation steps
  4. 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.

dataclass-native provides ways to generate native C++ and Rust structs, whose storage the Python classes use directly. Descriptors replace the dataclass attributes which marshal the values into the native classes. The initial implementation of these was in python but they have been superseded by native implementations for performance reasons.

Serialisation to JSON, msgpack and arrow is supported in python, Rust and C++. Going from arrow to parquet is a simple step, illustrated in the examples.

Write your object model using standard python dataclasses. Annotate with @native. Let dataclass-native generate you the C++ and Rust structs to use in your native code. Invoke native code taking your dataclasses using @native_function.

Status: early. Caveat Emptor. Tests cover foreseeable edge cases but there are naturally some compromises: 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. See Frozen or not.

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.

Frozen or not

A class may be frozen (@dataclass(frozen=True)) or not. Frozen is the better default: the differences are mostly of what the objects mean, not of speed.

Frozen Not frozen
Its fields Set once, when it is made May be set at any time
Held by another object By value: natively, within the struct which holds it By reference: what holds it holds that object, and sees what is set on it
Read from a field A view of it within a frozen object, without copying. A copy, if what holds it is not frozen The object which was given, itself
Shared[...] May be, so that it is written once, and is still shared when read May not be. It is written wherever it is held, so what was one object is read back as several
Hash As a dataclass has None
Numpy arrays Read-only May be written to
An object which holds itself Cannot be Can be, but is then not written as msgpack or JSON
Natively A plain struct A struct behind a reference-counted pointer: in Rust also behind a lock

Either kind may hold the other, and both are compared by value. The containers of both are immutable: a tuple of a class which is not frozen is set whole, though its objects may themselves be set.

In speed there is little between them. Setting a field costs about what reading one does, and making an object about the same of either kind: see Performance. Reading an object from a field, in nanoseconds, measured as there:

Read C++ Rust
A frozen object from a frozen one 148 166
A frozen object from one which is not, which is a copy 179 216
An object which is not frozen, which is the object given 97 157

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.

Generating Rust

dataclass-native generate rust --package my_schemas --out src

The generated modules use the crate dataclass_native, which is released with the Python package, at its version: so depend on the version of what generated them.

[dependencies]
dataclass_native = "=1.3.0"

It is also in the Python package, where dataclass-native rust-dir prints, to depend on by path.

This writes a file per module (src/my_schemas/trades.rs, the module my_schemas::trades once a crate has mod my_schemas;) of plain structs and enums. A union is an enum of its own, named for its class and field:

#[derive(Debug, Clone, PartialEq)]
pub struct Trade {
    pub id: i64,
    pub instrument: TradeInstrument,
    pub counterparty: dataclass_native::Shared<Party>,
    pub tags: Vec<String>,
    pub limits: Option<std::collections::BTreeMap<Currency, f64>>,
    pub executed: Option<dataclass_native::DateTime>,
}

They are written as msgpack, and read from it, as Python and C++ write and read them, with no Python:

use dataclass_native::msgpack::{from_msgpack, to_msgpack};

let data: Vec<u8> = to_msgpack(&trade)?;
let trade: Trade = from_msgpack(&data)?;

With the crate's feature json they are also serde's: each is Serialize and Deserialize, as JSON_FORMAT.md has it, so is written as the JSON which Python and C++ read:

use dataclass_native::json::{from_json, to_json};

let data: Vec<u8> = to_json(&trade)?;
let trade: Trade = from_json(&data)?;

serde_json::to_string(&trade) writes the same, but for the exponent of a float, which it has as 1e-5 where Python has 1e-05: either is read. The crate depends on nothing without the feature.

With its feature arrow they are held in Arrow tables, as ARROW_FORMAT.md has it, by arrow-rs: of version 59, as the arrays of two versions do not mix.

use dataclass_native::arrow::{from_arrow, to_arrow};

let tables = to_arrow(&trades)?;   // tables.root is a RecordBatch, and tables.shared one for each class shared
let trades: Vec<Trade> = from_arrow(&tables)?;

Which arrow-rs's parquet writes as files: the parquet-rust example writes and reads those which to_parquet and from_parquet do, in Rust alone.

To store Python's objects in them, as in the structs of C++ below, generate for pyo3 instead, which also writes src/my_schemas_native.rs:

dataclass-native generate pyo3 --package my_schemas --out src

One extension, my_schemas._native, is of the whole package. Its crate depends on pyo3 and on dataclass_native with its feature python, and its src/lib.rs is:

use pyo3::prelude::*;

mod my_schemas;
mod my_schemas_native;

#[pymodule(name = "_native")]
fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
    my_schemas_native::register(extension)
}

Built as an extension module (crate-type = ["cdylib"]) and placed in the package as _native, the classes of my_schemas are then bound to the Rust structs as they would be to those of C++. Rust writes and reads them as msgpack and as JSON. It holds them in Arrow tables too if the extension's crate has a feature arrow, which is ["dataclass_native/arrow"], and is built with it: else Python does, as arrow-rs is much to build. examples/functions-rust is such a project, built with maturin.

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.

A function of Rust is called likewise. It is added to the extension which holds the classes, my_schemas._native, which is then what its @native_function names:

use dataclass_native::python::{function, Held};

fn rating(trade: &Trade) -> i32 { ... }   // Plain Rust, knowing nothing of Python

#[pymodule(name = "_native")]
fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
    my_schemas_native::register(extension)?;
    // A Held is the struct in which the trade's fields are stored, not a copy of it
    function(extension, "rating", |trade: Held<Trade>| rating(&trade))
}

What it takes and gives are what fields may be of. If it gives a Result, Python raises its error: as a ValueError, if it is not an exception of pyo3's. See examples/functions-rust.

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. With pydantic installed (pip install dataclass-native[pydantic]), plain ones are instead written and read by it: in the same format, and several times faster, as Performance has it. 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. In Rust they are by arrow-rs's parquet, as the parquet-rust example does.

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: as strict, but a class whose binding is missing behaves as a plain dataclass.
  • pure: @native returns 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.

Performance

What it costs to hold objects natively, and what is gained by it. The times are the least of five runs, on an Apple M1 with Python 3.14, of extensions built for release: uv run python tests/performance.py prints these tables, of the classes of tests/schemas.

  • pure: plain dataclasses, as Python has them.
  • C++ and Rust: bound to the structs of each, whose extension reads and sets fields itself. C++'s does as of 1.1.0.
  • Python's descriptors: the same, read and set by way of Python, as an extension built before it did so is.
Nanoseconds to pure C++ Rust C++, Python's descriptors Rust, Python's descriptors
Make Money(1.5, Currency.EUR) 158 304 438 842 900
Make a Trade, of 19 fields 1,115 2,451 2,955 6,162 6,795
Make a Customer, which is not frozen 104 337 551 1,444 1,553
Read a float 9 29 45 113 111
Read an enum 18 25 40 175 190
Read a str 9 39 55 123 121
Read a nested object 17 161 171 299 326
Read a Shared object 9 144 212 214 265
Read a tuple of 3 strs 9 104 173 215 250
Read an array of 1,000 floats 9 308 420 407 503
Set an int 17 25 42 132 133
Set a str 9 30 61 139 151
Set a nested object 9 58 110 189 234

A bound object is slower to make and to read than a plain dataclass, as each field is converted to and from what the struct holds, where Python only keeps a reference: by some three times for a number in C++, and five in Rust, and more for what Python must make an object of each time it is read. An array is not copied, whatever its size. A field which is given its default is not set when an object is made, as the struct already holds it: so a class with many defaults, as Trade has, costs less to make than its fields would to set.

What is gained is in what native code then does with the structs, without Python: as in serialising. An Order here is of two customers, each with two addresses: 15 values, in 7 objects. Arrow is of 10,000 of them.

Microseconds, for each Order, to pure pure, with pydantic C++ Rust
Write msgpack 8.8 1.9 1.8
Read msgpack 24.6 2.6 2.7
Write JSON 10.9 3.5 2.3 2.0
Read JSON 13.6 3.6 3.2 2.7
Write Arrow 11.3 0.4 0.3
Read Arrow 9.4 0.7 0.8

C++ and Rust write and read the structs themselves: Rust's Arrow with the feature arrow of its crate, without which Python does it, reading each field from the struct, which is slower than pure. With pydantic installed, it writes and reads the JSON of plain dataclasses, in place of Python: which has no part in msgpack or Arrow.

Examples

examples has projects to copy from: a schema stored natively and one with C++ functions, each built by scikit-build-core; the same functions in Rust, built by maturin; and programs which write Parquet files, one of C++, with Arrow C++, and one of Rust, with arrow-rs.

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
uv run python tests/performance.py   # Then the tables of Performance, above: it also needs cargo

CI runs the same hooks (uv run pre-commit run --all-files) and the tests, on Linux, macOS and Windows.

About

Python dataclasses as a data description language, using native classes for storage

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages