From 0f9ef438d671d647d056c88b12e39ba0e30cc458 Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Mon, 30 Nov 2026 00:04:29 +0000 Subject: [PATCH 1/2] Do not set a default which the struct already holds, of an object being made: and make the crate 1.3.0 --- DESIGN.md | 10 ++++ README.md | 43 +++++++------- examples/functions-rust/Cargo.toml | 2 +- examples/parquet-rust/Cargo.toml | 2 +- src/dataclass_native/_runtime.py | 38 ++++++++++++- .../include/dataclass_native/python.hpp | 53 +++++++++++++++++ src/dataclass_native/rust/Cargo.toml | 2 +- src/dataclass_native/rust/src/fields.rs | 57 +++++++++++++++---- tests/test_bindings.py | 27 +++++++++ tests/test_mutable.py | 8 +++ tests/test_pyo3.py | 13 ++++- 11 files changed, 217 insertions(+), 38 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 567a44b..73eb463 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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 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 diff --git a/README.md b/README.md index 1963ec2..6988bd7 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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`. diff --git a/examples/functions-rust/Cargo.toml b/examples/functions-rust/Cargo.toml index 2489167..119c55b 100644 --- a/examples/functions-rust/Cargo.toml +++ b/examples/functions-rust/Cargo.toml @@ -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" diff --git a/examples/parquet-rust/Cargo.toml b/examples/parquet-rust/Cargo.toml index e4f738b..51234e3 100644 --- a/examples/parquet-rust/Cargo.toml +++ b/examples/parquet-rust/Cargo.toml @@ -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 diff --git a/src/dataclass_native/_runtime.py b/src/dataclass_native/_runtime.py index c3b98bd..d72d350 100644 --- a/src/dataclass_native/_runtime.py +++ b/src/dataclass_native/_runtime.py @@ -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__" @@ -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() @@ -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 @@ -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 @@ -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: @@ -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) diff --git a/src/dataclass_native/include/dataclass_native/python.hpp b/src/dataclass_native/include/dataclass_native/python.hpp index 4826347..f880ce1 100644 --- a/src/dataclass_native/include/dataclass_native/python.hpp +++ b/src/dataclass_native/include/dataclass_native/python.hpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -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 { @@ -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() @@ -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 = @@ -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; } @@ -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; } @@ -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(field)); return reinterpret_cast(field); } @@ -856,6 +885,20 @@ namespace dataclass_native::python return nullptr; auto* field = reinterpret_cast(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; @@ -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 + bool unset(PyObject* handle) + { + static const T fresh{}; + return member_of(handle) == fresh.*std::get(Reflect::fields).member; + } + // By name, the descriptor of each field of a struct: for dataclass_native._runtime to bind to its class template nanobind::dict fields() @@ -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) + reinterpret_cast(field)->unset = &unset; result[key] = nanobind::steal(field); }; [&](std::index_sequence) diff --git a/src/dataclass_native/rust/Cargo.toml b/src/dataclass_native/rust/Cargo.toml index 3fda3e3..75470d8 100644 --- a/src/dataclass_native/rust/Cargo.toml +++ b/src/dataclass_native/rust/Cargo.toml @@ -3,7 +3,7 @@ [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" +version = "1.3.0" edition = "2021" description = "Types used by the Rust generated by dataclass-native" license = "MIT" diff --git a/src/dataclass_native/rust/src/fields.rs b/src/dataclass_native/rust/src/fields.rs index c164ec7..11ea773 100644 --- a/src/dataclass_native/rust/src/fields.rs +++ b/src/dataclass_native/rust/src/fields.rs @@ -7,7 +7,7 @@ use pyo3::exceptions::{PyAttributeError, PyOverflowError, PyTypeError, PyValueEr use pyo3::prelude::*; use pyo3::types::{PyCFunction, PyDict, PyString, PyTuple, PyType}; use pyo3::{ffi, intern, PyTraverseError, PyVisit}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; /// What a field is told by dataclass_native._runtime, of what it could not know: with which a value is made as /// Python is to have it, not as Python would convert it @@ -82,6 +82,9 @@ trait Member: Send + Sync { /// From what the extension is given fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()>; + /// Whether the field is still what it is of a struct newly made: its default + fn unset(&self, handle: &Bound<'_, PyAny>) -> PyResult; + /// From what Python has, if it can be taken with what was told: giving whether it was fn take<'py>(&self, handle: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult; @@ -91,9 +94,15 @@ trait Member: Send + Sync { struct OfFrozen { read: fn(&T) -> &M, written: fn(&mut T) -> &mut M, + /// A struct newly made, which is made when first needed + fresh: OnceLock, } -impl Member for OfFrozen { +impl Member for OfFrozen { + fn unset(&self, handle: &Bound<'_, PyAny>) -> PyResult { + Ok((self.read)(&*T::unwrap(handle)?) == (self.read)(self.fresh.get_or_init(T::default))) + } + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { (self.read)(&*T::unwrap(handle)?).to_native(handle.py()) } @@ -123,7 +132,11 @@ impl Member for OfFrozen { /// A field of a frozen struct which is itself one: read where it is, not copied struct Within(OfFrozen); -impl Member for Within { +impl Member for Within { + fn unset(&self, handle: &Bound<'_, PyAny>) -> PyResult { + self.0.unset(handle) + } + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { M::wrap(handle.py(), T::unwrap(handle)?.member(self.0.read)) } @@ -153,9 +166,14 @@ impl Member for Within { struct OfChanging { read: fn(&T) -> &M, written: fn(&mut T) -> &mut M, + fresh: OnceLock, } -impl Member for OfChanging { +impl Member for OfChanging { + fn unset(&self, handle: &Bound<'_, PyAny>) -> PyResult { + Ok((self.read)(&T::unwrap(handle)?.read()) == (self.read)(self.fresh.get_or_init(T::default))) + } + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { (self.read)(&T::unwrap(handle)?.read()).to_native(handle.py()) } @@ -210,33 +228,33 @@ impl<'py> Fields<'py> { } /// A field of a frozen struct, by what gives it of one - pub fn frozen( + pub fn frozen( &self, name: &str, read: fn(&T) -> &M, written: fn(&mut T) -> &mut M, ) -> PyResult<()> { - self.add(name, OfFrozen { read, written }) + self.add(name, OfFrozen { read, written, fresh: OnceLock::new() }) } /// A field of a frozen struct which is itself a frozen struct - pub fn within( + pub fn within( &self, name: &str, read: fn(&T) -> &M, written: fn(&mut T) -> &mut M, ) -> PyResult<()> { - self.add(name, Within(OfFrozen { read, written })) + self.add(name, Within(OfFrozen { read, written, fresh: OnceLock::new() })) } /// A field of a struct which is not frozen - pub fn changing( + pub fn changing( &self, name: &str, read: fn(&T) -> &M, written: fn(&mut T) -> &mut M, ) -> PyResult<()> { - self.add(name, OfChanging { read, written }) + self.add(name, OfChanging { read, written, fresh: OnceLock::new() }) } } @@ -249,6 +267,10 @@ struct Bound_ { members: Option>, wraps: Option>, direct: bool, + /// The field's default in Python, if a native object newly made already holds it: so that it need not be set + /// again. Told by what it is: or by what it equals, if it is made anew for each object + fresh: Option>, + made: bool, } /// The descriptor of a field of a bound class: reads and sets the member of the native object of an instance @@ -280,6 +302,9 @@ impl Field { direct: bool, ) -> PyResult { let default = fallback.getattr("default")?; + // What the runtime found a native object newly made to hold: nothing, of a runtime before it looked + let fresh = fallback.getattr("fresh").ok().filter(|fresh| !fresh.is(&missing)); + let made = fallback.getattr("made").is_ok_and(|made| made.is_truthy().unwrap_or(false)); Ok(Field { name: self.name.clone_ref(py), native: self.native.clone_ref(py), @@ -293,6 +318,8 @@ impl Field { members: members.map(Bound::unbind), wraps: wraps.map(Bound::unbind), direct, + made: made && fresh.is_some(), + fresh: fresh.map(Bound::unbind), }), }) } @@ -341,6 +368,14 @@ impl Field { }; let of_native = handle.get_type().is(&self.native); + // The default, of a field which holds it still: as all of an object being made are, so there is nothing + // to set + if let Some(fresh) = bound.fresh.as_ref().map(|fresh| fresh.bind(py)).filter(|_| of_native) { + let equal = || value.get_type().is(&fresh.get_type()) && value.eq(fresh).unwrap_or(false); + if (value.is(fresh) || (bound.made && equal())) && self.member.unset(&handle).unwrap_or(false) { + return Ok(()); + } + } let set = || -> PyResult<()> { let Some(to_native) = bound.to_native.as_ref() else { return if of_native { self.member.set(&handle, value) } else { handle.setattr(&self.name, value) }; @@ -378,7 +413,7 @@ impl Field { visit.call(&self.native)?; if let Some(bound) = &self.bound { visit.call(&bound.fallback)?; - for held in [&bound.default, &bound.to_native, &bound.from_native].into_iter().flatten() { + for held in [&bound.default, &bound.to_native, &bound.from_native, &bound.fresh].into_iter().flatten() { visit.call(held)?; } if let Some(members) = &bound.members { diff --git a/tests/test_bindings.py b/tests/test_bindings.py index 6d99e8d..d1c8b29 100644 --- a/tests/test_bindings.py +++ b/tests/test_bindings.py @@ -460,3 +460,30 @@ def test_extension_built_before_it_had_descriptors(built): before = "del extension.__fields__, extension.__maker__" lines = _run(built, Mode.STRICT, _DESCRIPTORS.format(before=before)).splitlines() assert lines == ["_Field function", *_AS_DESCRIBED] + + +# A class as the extension's, but of another default than the extension was built with: as when one has been changed +_OTHER_DEFAULT = """ + import dataclasses + from dataclass_native import native + from schemas.common import Currency + + source = ( + "@native\\n" + "@dataclass(frozen=True)\\n" + "class Money:\\n" + " amount: float\\n" + " currency: Currency = Currency.GBP\\n" + ) + scope = {"__name__": "schemas.common", "native": native, "dataclass": dataclasses.dataclass, "Currency": Currency} + exec(source, scope) + Money = scope["Money"] + money = Money(1.0) + print(list(vars(money)), money.currency, Money(1.0, Currency.USD).currency, Money(1.0, Currency.GBP).currency) +""" +_OWN_DEFAULT = ["['__native__']", "Currency.GBP", "Currency.USD", "Currency.GBP"] + + +def test_default_other_than_the_extensions(built): + """Which is the class's own: a default is not set only where a native object newly made is found to hold it""" + assert _run(built, Mode.STRICT, _OTHER_DEFAULT).split() == _OWN_DEFAULT diff --git a/tests/test_mutable.py b/tests/test_mutable.py index 144ad87..ab72109 100644 --- a/tests/test_mutable.py +++ b/tests/test_mutable.py @@ -67,6 +67,14 @@ def test_fields_are_set(): assert node.next.name == "b" node.next = None assert node.next is None + # A default is set as any other value is, once the field is of another: though not of an object being made + for age in (0, 5, Customer.age): + customer.age = age + assert customer.age == age + for tags in ((), ("c",), Customer.tags): + customer.tags = tags + assert customer.tags == tags + customer.age, customer.tags = 31, ("a", "b") if BOUND: assert list(vars(customer)) == ["__native__"] invalid: Any = "old" diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index 6bc6f1b..e7162f4 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -9,7 +9,13 @@ from pathlib import Path import pytest -from test_bindings import _AS_DESCRIBED, _DESCRIPTORS, _run +from test_bindings import ( + _AS_DESCRIBED, + _DESCRIPTORS, + _OTHER_DEFAULT, + _OWN_DEFAULT, + _run, +) from dataclass_native import ENV_VAR, Mode, rust_dir from dataclass_native.backends import pyo3 @@ -311,3 +317,8 @@ def test_fields(built, before, types): ) lines = _run(built, Mode.STRICT, script.format(before=before)).splitlines() assert lines == [types, *_AS_DESCRIBED] + + +def test_default_other_than_the_extensions(built): + """Which is the class's own: as of C++""" + assert _run(built, Mode.STRICT, _OTHER_DEFAULT).split() == _OWN_DEFAULT From 1bed5e2e6959b0a8402d989dfeb784919d4f9e90 Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Mon, 30 Nov 2026 10:30:02 +0000 Subject: [PATCH 2/2] Take the crate's version from the tag when it is released --- .github/workflows/release.yml | 17 +++++++++-------- DESIGN.md | 6 +++--- src/dataclass_native/rust/Cargo.toml | 4 ++-- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c93af1c..d11e246 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 @@ -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: @@ -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 }} diff --git a/DESIGN.md b/DESIGN.md index 73eb463..c3f1f47 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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++. diff --git a/src/dataclass_native/rust/Cargo.toml b/src/dataclass_native/rust/Cargo.toml index 75470d8..cb9b5e0 100644 --- a/src/dataclass_native/rust/Cargo.toml +++ b/src/dataclass_native/rust/Cargo.toml @@ -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.3.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"