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
14 changes: 10 additions & 4 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,13 @@ the structs, by [pyo3](https://pyo3.rs), as nanobind does in those of C++.
- pyo3 says an int which is too great for its field is an `OverflowError`: the runtime makes of it the
`TypeError` which any value a field cannot be is.

Not yet in Rust, so done by Python for what is held in it: msgpack, JSON and Arrow. Nor are the descriptors of
fields which C++ has, so a field is read and set by way of Python.
- The extension has the `__fields__` and `__maker__` which one of C++ has, in each of its modules, so a field
is read and set, and an object made, without Python: by the crate's `Field`, which the generated code gives
what reads and writes the field of a struct. A type says how it is made as Python itself is to have it, and
taken from that, with what the field is told: an enum by its members, a frozen struct by its class, and a
tuple or a frozenset of what is as Python has it. The rest, Python's converters do, as for C++.

Not yet in Rust, so done by Python for what is held in it: msgpack, JSON and Arrow.

## Python runtime

Expand Down Expand Up @@ -418,8 +423,9 @@ what an object is made from, before the native class checks it.
and their defaults, generated as modules which cargo compiles, with a crate of the types they use which
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. To come: msgpack, JSON and Arrow in Rust, which Python does until then; the
descriptors of fields which C++ has; and an example built with maturin.
called as those of C++ are, and fields read and set by descriptors of the extension's own, as those of
C++ are. To come: msgpack, JSON and Arrow in Rust, which Python does until then; and an example built
with maturin.
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
55 changes: 28 additions & 27 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -351,41 +351,42 @@ Apple M1 with Python 3.14, of extensions built for release: `uv run python tests
tables, of the classes of [tests/schemas](tests/schemas).

- `pure`: plain dataclasses, as Python has them.
- C++: bound to the C++ structs, whose extension reads and sets fields itself, as of 1.1.0.
- C++, Python's descriptors: the same, read and set by way of Python, as an extension built by 1.0.0 is.
- Rust: bound to the Rust structs. Its extension does not yet read and set fields itself, so Python does.

| Nanoseconds to | `pure` | C++ | C++, Python's descriptors | Rust |
|---|---:|---:|---:|---:|
| Make `Money(1.5, Currency.EUR)` | 156 | 293 | 840 | 891 |
| Make a `Trade`, of 19 fields | 1,113 | 3,537 | 6,129 | 6,771 |
| Make a `Customer`, which is not frozen | 103 | 339 | 1,436 | 1,542 |
| Read a float | 9 | 29 | 113 | 111 |
| Read an enum | 17 | 25 | 176 | 186 |
| Read a str | 9 | 37 | 121 | 120 |
| Read a nested object | 17 | 147 | 295 | 320 |
| Read a `Shared` object | 9 | 139 | 215 | 258 |
| Read a tuple of 3 strs | 9 | 104 | 210 | 247 |
| Read an array of 1,000 floats | 9 | 301 | 394 | 723 |
| Set an int | 17 | 24 | 139 | 134 |
| Set a str | 9 | 30 | 147 | 150 |
| Set a nested object | 9 | 58 | 195 | 233 |
- 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)` | 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 |

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, and more for what
Python must make an object of each time it is read. An array is not copied, whatever its size.
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.

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.8 | 1.9 | 18.1 |
| Read msgpack | 24.3 | 2.6 | 36.5 |
| Write JSON | 10.7 | 2.3 | 20.1 |
| Read JSON | 13.5 | 3.1 | 25.8 |
| Write Arrow | 11.2 | 0.4 | 19.0 |
| Read Arrow | 9.3 | 0.7 | 19.6 |
| Write msgpack | 8.9 | 2.0 | 15.0 |
| Read msgpack | 24.5 | 2.7 | 31.1 |
| Write JSON | 10.8 | 2.4 | 17.0 |
| Read JSON | 13.6 | 3.2 | 20.5 |
| Write Arrow | 11.3 | 0.4 | 16.1 |
| Read Arrow | 9.4 | 0.8 | 14.2 |

C++ writes and reads the structs itself. Rust does not yet, so Python does, reading each field from the struct:
which is slower than `pure`, until Rust has its own.
Expand Down
81 changes: 60 additions & 21 deletions src/dataclass_native/backends/pyo3.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:
f"// Generated by dataclass-native from {package}: do not edit\n"
f"//! The classes which hold Python's objects of {package} in the structs generated for it. `register` adds\n"
f"//! them to an extension module, which is to be {package}._native\n"
"#![allow(non_camel_case_types, non_snake_case, clippy::all)]\n\n"
f"use {RUNTIME}::python::{{member, Changing, Frozen, Held, Native}};\n"
"#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, clippy::all)]\n\n"
f"use {RUNTIME}::python::{{maker, member, Changing, Fields, Frozen, Held, Native, Told}};\n"
f"use {RUNTIME}::Mutable;\n"
"use pyo3::exceptions::PyTypeError;\n"
"use pyo3::prelude::*;\n"
Expand All @@ -75,7 +75,7 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:
for module in modules:
generator = _ModuleGenerator(schema, module)
generator.generate()
added, hashes = [], []
added, hashes, structs = [], [], []
for enum in module.enums:
parts.append(_enum(enum))
added.append(_class(enum.module, enum.name))
Expand All @@ -86,7 +86,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:
parts.append(_struct(struct))
added.append(_class(struct.module, struct.name))
hashes.append((struct.name, s.schema_hash(struct)))
registered.append(_registered(package, module.name, added, hashes))
structs.append((struct.name, added[-1]))
registered.append(_registered(module.name, added, hashes, structs))

parts.append(
f"/// Adds a module for each schema module of {package} to an extension module, which is to be\n"
Expand All @@ -98,7 +99,10 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str:


def _registered(
package: str, module: str, classes: list[str], hashes: list[tuple[str, str]]
module: str,
classes: list[str],
hashes: list[tuple[str, str]],
structs: list[tuple[str, str]],
) -> str:
within = module.split(".")[1:]
lines = [
Expand All @@ -123,7 +127,18 @@ def _registered(
lines += [
f' schema.set_item("{name}", "{digest}")?;\n' for name, digest in hashes
]
lines += [' module.add("__schema__", schema)?;\n', " }\n"]
lines.append(' module.add("__schema__", schema)?;\n')
# What reads, sets and makes the objects of its classes without Python
lines.append(" let fields = PyDict::new(py);\n")
lines += [
f' fields.set_item("{name}", {cls}::fields(py)?)?;\n'
for name, cls in structs
]
lines += [
' module.add("__fields__", fields)?;\n',
' module.add("__maker__", maker(py)?)?;\n',
" }\n",
]
return "".join(lines)


Expand All @@ -149,8 +164,18 @@ def _enum(enum: s.Enum) -> str:
f" let held = value.cast_exact::<{name}>()\n"
f' .map_err(|_| PyTypeError::new_err("not a {enum.name}"))?;\n'
f" Ok(match held.get() {{\n{back} }})\n"
" }\n\n"
" fn to_python<'py>(&self, _py: Python<'py>, told: &Told<'_, 'py>) -> PyResult<Option<Bound<'py, PyAny>>> {\n"
f" told.member({name}__MEMBERS.iter().position(|member| member == self))\n"
" }\n\n"
" fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult<Option<Self>> {\n"
f" Ok(told.place(value).and_then(|at| {name}__MEMBERS.get(at).copied()))\n"
" }\n"
"}\n"
"}\n\n"
"/// In the order of Python's\n"
f"const {name}__MEMBERS: [{plain}; {len(members)}] = [\n"
+ "".join(f" {plain}::{m},\n" for m in members)
+ "];\n"
)


Expand Down Expand Up @@ -217,22 +242,28 @@ def _struct(struct: s.Struct) -> str:
" }\n"
)

by_value = (
# What reads and sets each field without Python
registered = []
for f in struct.fields:
match f.type:
case s.StructRef(mutable=False) if not struct.mutable:
kind = "within"
case _:
kind = "changing" if struct.mutable else "frozen"
field = identifier(f.name)
registered.append(
f' fields.{kind}::<{plain}, _>("{f.name}", |held| &held.{field}, |held| &mut held.{field})?;\n'
)
write = (
""
if struct.mutable
else (
"\n/// Held by value: so a copy of it\n"
f"impl Native for {plain} {{\n"
" fn to_native<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {\n"
f" <{plain} as Frozen>::wrap(py, Held::new(self.clone()))\n"
" }\n\n"
" fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self> {\n"
f" Ok((*<{plain} as Frozen>::unwrap(value)?).clone())\n"
" }\n\n"
" fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {\n"
f" <{plain} as Frozen>::wrap(py, Held::new(self))\n"
"\n fn write<R>(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult<R> {\n"
f" let held = value.cast_exact::<{name}>()\n"
f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n'
" let mut held = held.try_borrow_mut()?;\n"
" Ok(write(held.0.make_mut()))\n"
" }\n"
"}\n"
)
)
return (
Expand All @@ -247,8 +278,16 @@ def _struct(struct: s.Struct) -> str:
f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n'
" Ok(held.borrow().0.clone())\n"
" }\n"
"}\n"
f"{by_value}\n"
f"{write}"
"}\n\n"
f"impl {name} {{\n"
" fn fields(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {\n"
" let fields = Fields::new(py.get_type::<Self>());\n"
+ "".join(registered)
+ ""
" Ok(fields.into_dict())\n"
" }\n"
"}\n\n"
"#[pymethods]\n"
f"impl {name} {{\n"
" #[new]\n"
Expand Down
Loading
Loading