Metadata-Version: 2.4
Name: dataclass-native
Version: 1.1.0
Summary: Python dataclasses as a data description language, stored in generated C++ (and later Rust) structs
Author-email: Nick Young <nick.young.github@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Nick Young
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: C++
Classifier: Operating System :: OS Independent
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jinja2>=3.1.6
Provides-Extra: numpy
Requires-Dist: numpy>=2.5.5; extra == "numpy"
Provides-Extra: arrow
Requires-Dist: pyarrow>=26.0.1; extra == "arrow"
Requires-Dist: tzdata>=2026.6; sys_platform == "win32" and extra == "arrow"
Dynamic: license-file

# 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. Ability to run the python code without code generation steps
3. 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](DESIGN.md).

## Defining a schema

```python
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++

```shell
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:

```cpp
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](https://nanobind.readthedocs.io). With CMake:

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

```python
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:

```cpp
#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:

```python
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](examples/functions).

## Serialising

```python
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](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:

```cpp
#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

```python
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](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:

```cpp
#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

```python
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](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:

```cpp
#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](examples/parquet) 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`: 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.

## Examples

[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

```shell
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.

