Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ on:
tags: ["v*"]

jobs:
version:
# The crate is of the version of the tag, which the package is of: else neither is released
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: grep -qx "version = \"${GITHUB_REF_NAME#v}\"" src/dataclass_native/rust/Cargo.toml

publish:
needs: version
runs-on: ubuntu-latest
environment: pypi
permissions:
Expand All @@ -18,3 +26,13 @@ jobs:
- uses: astral-sh/setup-uv@v6
- run: uv build
- uses: pypa/gh-action-pypi-publish@release/v1

crate:
# dataclass_native, on crates.io: which the Rust that is generated uses
needs: version
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: cargo publish --manifest-path src/dataclass_native/rust/Cargo.toml
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
13 changes: 8 additions & 5 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,11 @@ which has a `mod.rs` naming what is in it: so `mod pkg;` in a crate whose `src`
package. A type of another module is named by way of what both are within, as `super::common::Money`, so the
modules may be anywhere in a crate.

- The generated code uses the crate `dataclass_native`, which is in the Python package and depends on nothing,
but on pyo3 for its feature `python`:
`dataclass-native rust-dir` prints its directory, to depend on by path.
- The generated code uses the crate `dataclass_native`, which depends on nothing but for its features: pyo3
for `python`, serde for `json` and arrow-rs for `arrow`. It is released to crates.io with the Python package,
at its version, as what is generated and the crate are of each other: the release is refused if the crate's
version is not the tag's. It is also in the Python package, where `dataclass-native rust-dir` prints, to
depend on by path.
- Names are Python's: a struct's, its fields', an enum's and its members', so `Currency::USD`. One which is a
keyword of Rust has `_` after it.
- A struct has the defaults of its class, as its `Default`: a field which has none has that of its type, as in C++.
Expand Down Expand Up @@ -453,8 +455,9 @@ what an object is made from, before the native class checks it.
depends on nothing; and Python's objects stored in the structs, as they are in those of C++, by an extension
generated for pyo3, with arrays which share their numbers with numpy; and functions written in Rust,
called as those of C++ are, and fields read and set by descriptors of the extension's own, as those of
C++ are; and msgpack, JSON by serde, and Arrow by arrow-rs. To come: Parquet from Rust alone, which
arrow-rs has; and an example built with maturin.
C++ are; and msgpack, JSON by serde, and Arrow by arrow-rs. Parquet from Rust alone needs arrow-rs's
`parquet`, which is not a dependency: the parquet-rust example uses it. The functions-rust example is an
extension built with maturin, whose `build.rs` generates the Rust when it is built.
6. **Done:** classes which are not frozen, whose fields may be set, held by reference, and whose arrays may be
written to. To come: lists.
7. JSON. The aim is that pydantic's `TypeAdapter` reads what this writes, and this reads what it writes: not that
Expand Down
77 changes: 64 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@ 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
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.

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

**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
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](DESIGN.md).

## Defining a schema
Expand Down Expand Up @@ -76,7 +83,7 @@ class Trade:

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.
set whole. See [Frozen or not](#frozen-or-not).

Containers are `tuple[T, ...]`, `tuple[A, B]`, `frozenset[T]` and `Mapping[K, V]`.

Expand All @@ -92,6 +99,35 @@ 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](#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++

```shell
Expand Down Expand Up @@ -122,9 +158,18 @@ Unchanged files are untouched, so builds don't rerun needlessly.

```shell
dataclass-native generate rust --package my_schemas --out src
dataclass-native rust-dir # dataclass_native's own crate, which the generated modules use: depend on it by path
```

The generated modules use the crate [`dataclass_native`](https://crates.io/crates/dataclass_native), which is
released with the Python package, at its version: so depend on the version of what generated them.

```toml
[dependencies]
dataclass_native = "=1.2.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:

Expand Down Expand Up @@ -172,6 +217,9 @@ let tables = to_arrow(&trades)?; // tables.root is a RecordBatch, and tables.s
let trades: Vec<Trade> = from_arrow(&tables)?;
```

Which arrow-rs's `parquet` writes as files: the [parquet-rust example](examples/parquet-rust) 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](https://pyo3.rs) instead, which also writes `src/my_schemas_native.rs`:

Expand All @@ -197,8 +245,9 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
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. An example
built with maturin is to come.
`["dataclass_native/arrow"]`, and is built with it: else Python does, as arrow-rs is much to build.
[examples/functions-rust](examples/functions-rust) is such a project, built with
[maturin](https://www.maturin.rs).

## Storing Python objects in the structs

Expand Down Expand Up @@ -290,7 +339,7 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
```

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.
`ValueError`, if it is not an exception of pyo3's. See [examples/functions-rust](examples/functions-rust).

## Serialising

Expand Down Expand Up @@ -363,7 +412,8 @@ auto tables = dataclass_native::arrow::to_arrow<Trade>(std::span<const Trade>(tr

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.
`from_parquet` do. In Rust they are by arrow-rs's `parquet`, as the
[parquet-rust example](examples/parquet-rust) does.

## Modes

Expand Down Expand Up @@ -428,7 +478,8 @@ which Python does it, reading each field from the struct, which is slower than `
## 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++.
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

Expand Down
8 changes: 8 additions & 0 deletions examples/functions-rust/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Generated from python/shop, by build.rs
/src/shop/
/src/shop_native.rs
/target/
Cargo.lock
# The extension, where maturin develop puts it
/python/shop/*.so
/python/shop/*.pyd
25 changes: 25 additions & 0 deletions examples/functions-rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# The extension shop._native: which holds the objects of the package's classes in Rust, and has its functions
[package]
name = "shop"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
name = "_native"
crate-type = ["cdylib"]

# With arrow, the classes are held in Arrow tables by the extension: else by Python, as arrow-rs is much to build.
# maturin builds with it if pyproject.toml's [tool.maturin] has features = ["arrow"]
[features]
arrow = ["dataclass_native/arrow"]

[dependencies]
# dataclass-native's own crate. In a project of your own it is that of crates.io, of the version of the Python
# package which generates the Rust: dataclass_native = { version = "=1.2.0", features = ["python"] }. Here it is
# that of this repository
dataclass_native = { path = "../../src/dataclass_native/rust", features = ["python"] }
pyo3 = "0.30"

[build-dependencies]
pyo3-build-config = "0.30"
23 changes: 23 additions & 0 deletions examples/functions-rust/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! Generates the Rust of the package, src/shop and src/shop_native.rs, from python/shop: as
//! `dataclass-native generate pyo3` does. By the Python which the extension is built for, which is to have
//! dataclass-native installed: as that which builds it has, by pyproject.toml's build-system.

use std::process::Command;

fn main() {
println!("cargo:rerun-if-changed=python/shop");
println!("cargo:rerun-if-env-changed=PYO3_PYTHON");
// Which maturin says: or python3, of cargo alone
let python = std::env::var("PYO3_PYTHON").unwrap_or_else(|_| "python3".to_string());
let generated = Command::new(&python)
.args(["-m", "dataclass_native", "generate", "pyo3", "--package", "shop", "--out", "src"])
.env("PYTHONPATH", "python")
// Which would else be in the wheel, with the package
.env("PYTHONDONTWRITEBYTECODE", "1")
.status()
.unwrap_or_else(|error| panic!("{python} could not be run, to generate the Rust of the package: {error}"));
assert!(generated.success(), "dataclass-native did not generate the Rust of the package");

// What links an extension, where cargo alone builds it: maturin does so itself
pyo3_build_config::add_extension_module_link_args();
}
22 changes: 22 additions & 0 deletions examples/functions-rust/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import datetime as dt

from dataclass_native import mode
from shop.model import Address, Customer, Line, Order
from shop.pricing import ship, total

alice = Customer(1, "Alice", Address("1 High St", "Leeds", "LS1 1AA"))
order = Order(
id=100,
customer=alice,
lines=(Line("widget", 2, 9.99), Line("gadget", 1, 24.50)),
placed=dt.date(2026, 11, 27),
)

print(f"Mode: {mode()}")
print(f"Total: {total(order):.2f}")

shipped = ship(order)
print(f"Shipped to: {shipped.ship_to}")
print(f"Still sharing the customer: {shipped.customer is alice}")
print(f"Or to: {ship(order, Address('2 Low Rd', 'York', 'YO1 2BB')).ship_to}")
print(f"The order itself is unchanged: {order.status}")
18 changes: 18 additions & 0 deletions examples/functions-rust/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[project]
name = "shop"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = ["dataclass-native"]

# maturin builds Cargo.toml's crate, and puts it into the wheel as shop._native, with the package of python/
[build-system]
requires = ["maturin>=1.9.4,<2", "dataclass-native"]
build-backend = "maturin"

[tool.maturin]
python-source = "python"
module-name = "shop._native"

# This repository's dataclass-native, to run and to build with: not needed in a project of your own
[tool.uv.sources]
dataclass-native = { path = "../..", editable = true }
Empty file.
48 changes: 48 additions & 0 deletions examples/functions-rust/python/shop/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import datetime as dt
from dataclasses import dataclass
from enum import Enum, auto

from dataclass_native import Int32, Shared, native


class Status(Enum):
PENDING = auto()
SHIPPED = auto()
DELIVERED = auto()


@native
@dataclass(frozen=True)
class Address:
street: str
city: str
postcode: str
country: str = "GB"


@native
@dataclass(frozen=True)
class Customer:
id: int
name: str
address: Address
email: str | None = None


@native
@dataclass(frozen=True)
class Line:
sku: str
quantity: Int32
unit_price: float


@native
@dataclass(frozen=True)
class Order:
id: int
customer: Shared[Customer] # Shared by a customer's orders, not copied into each
lines: tuple[Line, ...]
placed: dt.date
status: Status = Status.PENDING
ship_to: Address | None = None # The customer's address, if None
18 changes: 18 additions & 0 deletions examples/functions-rust/python/shop/pricing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Functions of orders, implemented in Rust by src/pricing.rs: their bodies are what runs in pure mode"""

from dataclasses import replace

from dataclass_native import native_function

from .model import Address, Order, Status


@native_function("._native")
def total(order: Order) -> float:
return sum(line.quantity * line.unit_price for line in order.lines)


@native_function("._native")
def ship(order: Order, to: Address | None = None) -> Order:
"""The order, shipped to the address given, or else to its customer's"""
return replace(order, status=Status.SHIPPED, ship_to=to or order.customer.address)
20 changes: 20 additions & 0 deletions examples/functions-rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//! The extension shop._native: the classes which hold Python's objects in the generated structs, and the functions
//! of pricing.rs, for those of python/shop/pricing.py

mod pricing;
// Generated from python/shop, by build.rs
#[allow(dead_code)]
mod shop;
mod shop_native;

use dataclass_native::python::{function, Held};
use pyo3::prelude::*;
use shop::model::{Address, Order};

#[pymodule(name = "_native")]
fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
shop_native::register(extension)?;
// A Held is the struct in which Python's order is stored, not a copy of it
function(extension, "total", |order: Held<Order>| pricing::total(&order))?;
function(extension, "ship", |order: Held<Order>, to: Option<Address>| pricing::ship(&order, to))
}
Loading
Loading