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
17 changes: 9 additions & 8 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ on:

jobs:
version:
# The crate is of the version of the tag, which the package is of: else neither is released
# The package and the crate are both of the tag's version: which is to be one a crate may have, 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
- run: '[[ "$GITHUB_REF_NAME" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]'

publish:
needs: version
Expand All @@ -20,11 +20,11 @@ jobs:
id-token: write
steps:
- uses: actions/checkout@v4
with:
# setuptools-scm derives the version from the tags
fetch-depth: 0
- uses: astral-sh/setup-uv@v6
- run: uv build
# The crate within the package is of the tag's version. As that changes a file, the version is given
# to setuptools-scm, which would otherwise derive one of a changed tree
- run: sed -i "s/^version = .*/version = \"${GITHUB_REF_NAME#v}\"/" src/dataclass_native/rust/Cargo.toml
- run: SETUPTOOLS_SCM_PRETEND_VERSION="${GITHUB_REF_NAME#v}" uv build
- uses: pypa/gh-action-pypi-publish@release/v1

crate:
Expand All @@ -33,6 +33,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: cargo publish --manifest-path src/dataclass_native/rust/Cargo.toml
- run: sed -i "s/^version = .*/version = \"${GITHUB_REF_NAME#v}\"/" src/dataclass_native/rust/Cargo.toml
- run: cargo publish --allow-dirty --manifest-path src/dataclass_native/rust/Cargo.toml
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
16 changes: 13 additions & 3 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,9 @@ modules may be anywhere in a crate.

- 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.
at its version, as what is generated and the crate are of each other: which is the tag's, written to its
`Cargo.toml` when it is released. 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 @@ -345,6 +345,16 @@ This is all that the Python runtime asks of an extension, whatever it is written
whatever it is given which is not exactly what it takes, it asks nanobind, and Python's converters where there
is one: so what is rejected, and how, is as it was. An extension built before it had them is used with
descriptors written in Python, which do the same.
- A default is not set where the struct already holds it. The struct which is generated has the defaults of its
class, and the dataclass's own `__init__` sets every field, whether given or not: so of an object being made,
each default would be converted and set though it is there already. When a class is bound, a native object is
made and each of its fields read: where one is the class's default, the descriptor is told so, and then sets
nothing when it is given that default and the struct's field is still what it is of a struct newly made. So it
is right of an object which is not frozen, of which a field may be set back to its default: and of an extension
built before a default was changed, of which that default is then set as before. Defaults are thus still not of
the schema's hash. A default is told by which object it is: or by what it equals, if it is of a
`default_factory`. One which is held by reference is not skipped, as it is which object it is that matters,
unless it is None or holds nothing. The descriptors written in Python do not do this.
- A class which is not frozen is held by reference, by whatever holds it: natively a `dataclass_native::Mutable<A>`,
a reference-counted pointer to it. So the object a field is read as is the object it was given, and what is set
on it is seen by all which hold it. Copies of a struct share it, as a shallow copy does in Python. It is compared
Expand Down
43 changes: 22 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ released with the Python package, at its version: so depend on the version of wh

```toml
[dependencies]
dataclass_native = "=1.2.0"
dataclass_native = "=1.3.0"
```

It is also in the Python package, where `dataclass-native rust-dir` prints, to depend on by path.
Expand Down Expand Up @@ -441,36 +441,37 @@ tables, of the classes of [tests/schemas](tests/schemas).

| Nanoseconds to | `pure` | C++ | Rust | C++, Python's descriptors | Rust, Python's descriptors |
|---|---:|---:|---:|---:|---:|
| Make `Money(1.5, Currency.EUR)` | 159 | 300 | 431 | 838 | 904 |
| Make a `Trade`, of 19 fields | 1,126 | 3,568 | 4,006 | 6,293 | 6,705 |
| Make a `Customer`, which is not frozen | 104 | 338 | 563 | 1,447 | 1,566 |
| Read a float | 9 | 29 | 46 | 113 | 112 |
| Read an enum | 18 | 25 | 40 | 174 | 187 |
| Read a str | 9 | 39 | 56 | 121 | 119 |
| Read a nested object | 18 | 153 | 169 | 298 | 312 |
| Read a `Shared` object | 9 | 149 | 203 | 217 | 262 |
| Read a tuple of 3 strs | 9 | 104 | 154 | 210 | 262 |
| Read an array of 1,000 floats | 9 | 299 | 418 | 400 | 485 |
| Set an int | 17 | 24 | 41 | 132 | 134 |
| Set a str | 9 | 30 | 60 | 139 | 152 |
| Set a nested object | 9 | 58 | 107 | 190 | 235 |
| 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.
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` | C++ | Rust |
|---|---:|---:|---:|
| Write msgpack | 8.9 | 1.9 | 1.8 |
| Read msgpack | 24.5 | 2.6 | 2.8 |
| Write JSON | 10.7 | 2.3 | 2.0 |
| Read JSON | 13.8 | 3.2 | 2.7 |
| Write Arrow | 11.5 | 0.4 | 0.3 |
| Read Arrow | 9.4 | 0.8 | 0.7 |
| Write msgpack | 8.8 | 1.9 | 1.8 |
| Read msgpack | 24.6 | 2.6 | 2.7 |
| Write JSON | 10.9 | 2.3 | 2.0 |
| Read JSON | 13.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`.
Expand Down
2 changes: 1 addition & 1 deletion examples/functions-rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ 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
# package which generates the Rust: dataclass_native = { version = "=1.3.0", features = ["python"] }. Here it is
# that of this repository
dataclass_native = { path = "../../src/dataclass_native/rust", features = ["python"] }
pyo3 = "0.30"
Expand Down
2 changes: 1 addition & 1 deletion examples/parquet-rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ publish = false

[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 = ["arrow"] }. Here it is
# package which generates the Rust: dataclass_native = { version = "=1.3.0", features = ["arrow"] }. Here it is
# that of this repository
dataclass_native = { path = "../../src/dataclass_native/rust", features = ["arrow"] }
# arrow-rs's Parquet, which dataclass-native does not depend on: of the version of arrow-rs which dataclass_native
Expand Down
38 changes: 36 additions & 2 deletions src/dataclass_native/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from . import schema as s
from ._mode import ENV_VAR, Mode
from ._native import NativeBindingError, extension_name
from .introspect import describe, resolve
from .introspect import describe, resolve, walk

HANDLE = "__native__"

Expand Down Expand Up @@ -68,6 +68,8 @@ def __init__(self, cls: type, native: type):
"""By name, the extension's own descriptor of the field, if it has them: and what it is told of the field"""
self.maker: Any = None
"""What gives the extension's own __new__ for the class, if it has one"""
self.plain: set[str] = set()
"""The fields whose values are no more than what they equal: so not what is held by reference, nor an array"""


_lock = RLock()
Expand Down Expand Up @@ -215,6 +217,8 @@ def _binding(cls: type) -> _Binding:
binding.maker = getattr(extension, "__maker__", None)
for f in struct.fields:
binding.fields[f.name] = _to_native(f.type), _from_native(f.type)
if not any(_by_reference(t) or isinstance(t, s.Array) for t in walk(f.type)):
binding.plain.add(f.name)
if f.name in descriptors:
inner = f.type.inner if isinstance(f.type, s.Optional) else f.type
# What it is told, to read and set without Python: the members of an enum, the class of a struct which
Expand Down Expand Up @@ -544,7 +548,7 @@ def _native_value_type(t: s.Type) -> type:
class _Field:
"""A field of a bound class: gets and sets the member of the instance's native object"""

__slots__ = ("default", "from_native", "name", "to_native")
__slots__ = ("default", "fresh", "from_native", "made", "name", "to_native")

def __init__(
self, name: str, default: Any, to_native: _Converter, from_native: _Converter
Expand All @@ -553,6 +557,11 @@ def __init__(
self.default = default
self.to_native = to_native
self.from_native = from_native
self.fresh: Any = MISSING
"""The field's default, if a native object newly made already holds it: which the extension's own descriptor
then need not set again, of an object being made"""
self.made = False
"""Whether that default is made anew for each object, so is told by what it equals, not by what it is"""

def __get__(self, obj: Any, owner: type | None = None) -> Any:
if obj is None:
Expand Down Expand Up @@ -630,13 +639,38 @@ def _setstate(self: Any, state: dict[str, Any]):
object.__setattr__(self, name, value)


def _fresh(binding: _Binding, f: Any, fresh: Any, field: _Field) -> tuple[Any, bool]:
"""The default of a field, if a native object newly made holds it: and whether it is made anew for each object"""
made = f.default_factory is not MISSING
try:
default = f.default_factory() if made else field.default
# None, and a container of nothing, are of no object: so may be the default even of what is held by
# reference, where which object it is matters
empty = default is None or (
isinstance(default, tuple | frozenset | Mapping) and not default
)
if default is MISSING or not (empty or f.name in binding.plain):
return MISSING, False
held = getattr(fresh, f.name)
if field.from_native and held is not None:
held = field.from_native(held)
return (default, made) if (held == default) is True else (MISSING, False)
except Exception: # noqa: BLE001
# Whatever a default or its comparison raises: it is then set as it was before
return MISSING, False


def _install(binding: _Binding):
cls = binding.cls
# As new, so holding what the native class has as its defaults: which may not be the class's own, if the
# extension was built before they were changed
fresh = binding.native() if binding.descriptors else None
for f in fields(cls):
# The attribute the dataclass has is its default, if any
default = getattr(cls, f.name, MISSING)
field: Any = _Field(f.name, default, *binding.fields[f.name])
if f.name in binding.descriptors:
field.fresh, field.made = _fresh(binding, f, fresh, field)
# Which does as it does, without Python: and reads an enum's member itself, if told them
descriptor, *told = binding.descriptors[f.name]
field = descriptor.bound(field, MISSING, *told)
Expand Down
53 changes: 53 additions & 0 deletions src/dataclass_native/include/dataclass_native/python.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <algorithm>
#include <chrono>
#include <concepts>
#include <cstdint>
#include <cstring>
#include <memory>
Expand Down Expand Up @@ -604,6 +605,8 @@ namespace dataclass_native::python
using Getter = PyObject* (*)(PyObject* handle, const FieldObject& field);
// Sets a member, and gives whether it did: it does not what it cannot itself convert, which is left to say why
using Setter = bool (*)(PyObject* handle, PyObject* value, const FieldObject& field);
// Whether a member is still what it is of a native object newly made: its default
using Unset = bool (*)(PyObject* handle);

struct FieldObject
{
Expand All @@ -627,6 +630,11 @@ namespace dataclass_native::python
Setter set;
// What the member is, of what is read or set without nanobind: else "other"
const char* kind;
// The field's default in Python, if a native object newly made already holds it: so that it need not be
// set again. Compared by what it is: or by what it equals, if it is made anew for each object
PyObject* fresh;
bool made;
Unset unset;
};

inline PyObject* handle_key()
Expand Down Expand Up @@ -710,6 +718,22 @@ namespace dataclass_native::python
return set ? 0 : -1;
}

// The default, of a field which holds it still: as all of an object being made are, so there is nothing
// to set
if (field->fresh && field->unset && Py_TYPE(handle) == field->native)
{
bool is_default = value == field->fresh;
if (!is_default && field->made && Py_TYPE(value) == Py_TYPE(field->fresh))
{
const int equal = PyObject_RichCompareBool(value, field->fresh, Py_EQ);
if (equal < 0)
PyErr_Clear();
is_default = equal == 1;
}
if (is_default && field->unset(handle))
return 0;
}

if (field->set && Py_TYPE(handle) == field->native && field->set(handle, value, *field))
return 0;
PyObject* converted =
Expand Down Expand Up @@ -739,6 +763,7 @@ namespace dataclass_native::python
Py_VISIT(field->from_native);
Py_VISIT(field->members);
Py_VISIT(field->wraps);
Py_VISIT(field->fresh);
Py_VISIT(Py_TYPE(self));
return 0;
}
Expand All @@ -754,6 +779,7 @@ namespace dataclass_native::python
Py_CLEAR(field->from_native);
Py_CLEAR(field->members);
Py_CLEAR(field->wraps);
Py_CLEAR(field->fresh);
return 0;
}

Expand Down Expand Up @@ -818,6 +844,9 @@ namespace dataclass_native::python
field->get = get;
field->set = set;
field->kind = kind;
field->fresh = nullptr;
field->made = false;
field->unset = nullptr;
PyObject_GC_Track(reinterpret_cast<PyObject*>(field));
return reinterpret_cast<PyObject*>(field);
}
Expand Down Expand Up @@ -856,6 +885,20 @@ namespace dataclass_native::python
return nullptr;
auto* field = reinterpret_cast<FieldObject*>(made);
field->fallback = Py_NewRef(fallback);
field->unset = prototype->unset;
// What the runtime found a native object newly made to hold: nothing, of a runtime before it looked
if (PyObject* fresh = PyObject_GetAttrString(fallback, "fresh"); !fresh)
PyErr_Clear();
else if (fresh == missing)
Py_DECREF(fresh);
else
{
field->fresh = fresh;
PyObject* each = PyObject_GetAttrString(fallback, "made");
field->made = each && PyObject_IsTrue(each) == 1;
Py_XDECREF(each);
PyErr_Clear();
}
// A default which is None is one: only what is missing is not
PyObject* held = PyObject_GetAttrString(fallback, "default");
field->fallback_default = held == missing ? (Py_XDECREF(held), nullptr) : held;
Expand Down Expand Up @@ -1288,6 +1331,14 @@ namespace dataclass_native::python
return nanobind::steal(PyCFunction_New(&definition, nullptr));
}

// Whether a member is what it is of a struct newly made
template <class T, std::size_t I>
bool unset(PyObject* handle)
{
static const T fresh{};
return member_of<T, I>(handle) == fresh.*std::get<I>(Reflect<T>::fields).member;
}

// By name, the descriptor of each field of a struct: for dataclass_native._runtime to bind to its class
template <class T>
nanobind::dict fields()
Expand Down Expand Up @@ -1319,6 +1370,8 @@ namespace dataclass_native::python
field = field_new(key.ptr(), native, nullptr, nullptr, "other");
if (!field)
throw nanobind::python_error();
if constexpr (std::equality_comparable<M>)
reinterpret_cast<FieldObject*>(field)->unset = &unset<T, I>;
result[key] = nanobind::steal(field);
};
[&]<std::size_t... I>(std::index_sequence<I...>)
Expand Down
4 changes: 2 additions & 2 deletions src/dataclass_native/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# `dataclass-native rust-dir` prints: it depends on nothing itself, but for its features arrow, json and python.
[package]
name = "dataclass_native"
# That of the Python package it is released with, which is the tag's: the release is refused if they differ
version = "1.2.0"
# That of the Python package it is released with, which is the tag's: written here when it is released
version = "0.0.0"
edition = "2021"
description = "Types used by the Rust generated by dataclass-native"
license = "MIT"
Expand Down
Loading
Loading