dataclass-native 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. dataclass_native/__init__.py +60 -0
  2. dataclass_native/__main__.py +5 -0
  3. dataclass_native/_arrow.py +822 -0
  4. dataclass_native/_json.py +783 -0
  5. dataclass_native/_mode.py +57 -0
  6. dataclass_native/_msgpack.py +207 -0
  7. dataclass_native/_native.py +234 -0
  8. dataclass_native/_runtime.py +607 -0
  9. dataclass_native/_version.py +24 -0
  10. dataclass_native/_wire.py +901 -0
  11. dataclass_native/arrays.py +13 -0
  12. dataclass_native/backends/__init__.py +0 -0
  13. dataclass_native/backends/bindings.py +74 -0
  14. dataclass_native/backends/cpp.py +574 -0
  15. dataclass_native/backends/templates/bindings.cpp.j2 +58 -0
  16. dataclass_native/backends/templates/extensions.cmake.j2 +12 -0
  17. dataclass_native/backends/templates/header.hpp.j2 +75 -0
  18. dataclass_native/cli.py +125 -0
  19. dataclass_native/cmake/dataclass_native-config.cmake +67 -0
  20. dataclass_native/include/dataclass_native/arrow.hpp +2022 -0
  21. dataclass_native/include/dataclass_native/json.hpp +1903 -0
  22. dataclass_native/include/dataclass_native/msgpack.hpp +1513 -0
  23. dataclass_native/include/dataclass_native/python.hpp +594 -0
  24. dataclass_native/include/dataclass_native/reflect.hpp +63 -0
  25. dataclass_native/include/dataclass_native/types.hpp +417 -0
  26. dataclass_native/introspect.py +811 -0
  27. dataclass_native/py.typed +0 -0
  28. dataclass_native/schema.py +553 -0
  29. dataclass_native/types.py +103 -0
  30. dataclass_native-1.0.0.dist-info/METADATA +339 -0
  31. dataclass_native-1.0.0.dist-info/RECORD +35 -0
  32. dataclass_native-1.0.0.dist-info/WHEEL +5 -0
  33. dataclass_native-1.0.0.dist-info/entry_points.txt +2 -0
  34. dataclass_native-1.0.0.dist-info/licenses/LICENSE +21 -0
  35. dataclass_native-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,57 @@
1
+ """Whether @native classes bind to their native equivalents, or behave as plain dataclasses"""
2
+
3
+ import os
4
+ from enum import StrEnum
5
+
6
+ ENV_VAR = "DATACLASS_NATIVE_MODE"
7
+
8
+
9
+ class Mode(StrEnum):
10
+ STRICT = "strict"
11
+ """Fields are stored in the native object, which must be available: a missing binding raises"""
12
+ MIXED = "mixed"
13
+ """As strict, but a class whose binding is missing behaves as a plain stdlib dataclass"""
14
+ PURE = "pure"
15
+ """@native returns its class unchanged: a plain stdlib dataclass"""
16
+
17
+
18
+ def _from_env() -> Mode:
19
+ value = os.environ.get(ENV_VAR, "").strip().lower()
20
+ if not value:
21
+ return Mode.STRICT
22
+ try:
23
+ return Mode(value)
24
+ except ValueError:
25
+ expected = ", ".join(m.value for m in Mode)
26
+ raise ValueError(
27
+ f"{ENV_VAR}={value!r} is invalid: expected one of {expected}"
28
+ ) from None
29
+
30
+
31
+ _mode = _from_env()
32
+ # Set once a class has been decorated, as it was decorated per the mode then in effect
33
+ _fixed = False
34
+
35
+
36
+ def mode() -> Mode:
37
+ """The mode in effect, from DATACLASS_NATIVE_MODE (strict by default) unless set by set_mode()"""
38
+ return _mode
39
+
40
+
41
+ def set_mode(new: Mode | str) -> None:
42
+ """Set the mode, which must happen before any @native class is defined, i.e. before importing schema modules"""
43
+ global _mode
44
+ new = Mode(new)
45
+ if _fixed and new is not _mode:
46
+ raise RuntimeError(
47
+ f"Cannot change the mode to {new.value!r}: @native classes have already been defined in mode "
48
+ f"{_mode.value!r}. Set it before importing schema modules, or via {ENV_VAR}"
49
+ )
50
+ _mode = new
51
+
52
+
53
+ def _fix_mode() -> Mode:
54
+ """The mode, which may no longer change, as a class is being decorated per it"""
55
+ global _fixed
56
+ _fixed = True
57
+ return _mode
@@ -0,0 +1,207 @@
1
+ """
2
+ The msgpack format, as much of it as the wire format uses: see WIRE_FORMAT.md. Written here, rather than taken from
3
+ the msgpack package, as it is small, and what is written must not vary with that package's version or options.
4
+ """
5
+
6
+ import struct
7
+ from typing import Any, NamedTuple
8
+
9
+
10
+ class Ext(NamedTuple):
11
+ """An extension value"""
12
+
13
+ code: int
14
+ data: bytes
15
+
16
+
17
+ def pack_nil(out: bytearray):
18
+ out.append(0xC0)
19
+
20
+
21
+ def pack_bool(out: bytearray, value: bool):
22
+ out.append(0xC3 if value else 0xC2)
23
+
24
+
25
+ def pack_int(out: bytearray, value: int):
26
+ """In as few bytes as hold it. Raises struct.error if it is not within 64 bits"""
27
+ if -32 <= value < 128:
28
+ out.append(value & 0xFF)
29
+ elif value >= 0:
30
+ if value < 1 << 8:
31
+ out += struct.pack(">BB", 0xCC, value)
32
+ elif value < 1 << 16:
33
+ out += struct.pack(">BH", 0xCD, value)
34
+ elif value < 1 << 32:
35
+ out += struct.pack(">BI", 0xCE, value)
36
+ else:
37
+ out += struct.pack(">BQ", 0xCF, value)
38
+ elif value >= -(1 << 7):
39
+ out += struct.pack(">Bb", 0xD0, value)
40
+ elif value >= -(1 << 15):
41
+ out += struct.pack(">Bh", 0xD1, value)
42
+ elif value >= -(1 << 31):
43
+ out += struct.pack(">Bi", 0xD2, value)
44
+ else:
45
+ out += struct.pack(">Bq", 0xD3, value)
46
+
47
+
48
+ def pack_float(out: bytearray, value: float, bits: int = 64):
49
+ """Raises OverflowError if it is too large for 32 bits"""
50
+ out += (
51
+ struct.pack(">Bf", 0xCA, value)
52
+ if bits == 32
53
+ else struct.pack(">Bd", 0xCB, value)
54
+ )
55
+
56
+
57
+ def _pack_length(
58
+ out: bytearray,
59
+ length: int,
60
+ inline: tuple[int, int] | None,
61
+ codes: tuple[int | None, int, int],
62
+ ):
63
+ """
64
+ A length, in the first of the forms which holds it: within the type's byte (inline: that byte, and the lengths
65
+ it has room for), or after a byte (codes) in 1, 2 or 4 bytes
66
+ """
67
+ if inline and length < inline[1]:
68
+ out.append(inline[0] | length)
69
+ elif codes[0] is not None and length < 1 << 8:
70
+ out += struct.pack(">BB", codes[0], length)
71
+ elif length < 1 << 16:
72
+ out += struct.pack(">BH", codes[1], length)
73
+ else:
74
+ out += struct.pack(">BI", codes[2], length)
75
+
76
+
77
+ def pack_str(out: bytearray, value: str):
78
+ data = value.encode()
79
+ _pack_length(out, len(data), (0xA0, 32), (0xD9, 0xDA, 0xDB))
80
+ out += data
81
+
82
+
83
+ def pack_bin(out: bytearray, value: bytes):
84
+ _pack_length(out, len(value), None, (0xC4, 0xC5, 0xC6))
85
+ out += value
86
+
87
+
88
+ def pack_array(out: bytearray, length: int):
89
+ """The start of an array, which its elements follow"""
90
+ _pack_length(out, length, (0x90, 16), (None, 0xDC, 0xDD))
91
+
92
+
93
+ def pack_map(out: bytearray, length: int):
94
+ """The start of a map, which its keys and values follow, alternately"""
95
+ _pack_length(out, length, (0x80, 16), (None, 0xDE, 0xDF))
96
+
97
+
98
+ _FIXED_EXT = {1: 0xD4, 2: 0xD5, 4: 0xD6, 8: 0xD7, 16: 0xD8}
99
+
100
+
101
+ def pack_ext(out: bytearray, code: int, data: bytes):
102
+ if fixed := _FIXED_EXT.get(len(data)):
103
+ out.append(fixed)
104
+ else:
105
+ _pack_length(out, len(data), None, (0xC7, 0xC8, 0xC9))
106
+ out += struct.pack(">b", code)
107
+ out += data
108
+
109
+
110
+ # By first byte: the format of the length, or of the number, which follows it
111
+ _LENGTHS = {
112
+ **{0xC4 + i: f for i, f in enumerate([">B", ">H", ">I"])},
113
+ **{0xC7 + i: f for i, f in enumerate([">B", ">H", ">I"])},
114
+ **{0xD9 + i: f for i, f in enumerate([">B", ">H", ">I"])},
115
+ **{0xDC + i: f for i, f in enumerate([">H", ">I", ">H", ">I"])},
116
+ }
117
+ _NUMBERS = {
118
+ 0xCA: ">f",
119
+ 0xCB: ">d",
120
+ **{
121
+ 0xCC + i: f
122
+ for i, f in enumerate([">B", ">H", ">I", ">Q", ">b", ">h", ">i", ">q"])
123
+ },
124
+ }
125
+
126
+
127
+ def unpack(data: bytes) -> Any:
128
+ """
129
+ The one value which data holds: None, a bool, int, float, str or bytes, a list, a dict or an Ext. Raises
130
+ ValueError if it is not one msgpack value, or has a map with a key twice
131
+ """
132
+ position = 0
133
+
134
+ def take(length: int) -> bytes:
135
+ nonlocal position
136
+ if position + length > len(data):
137
+ raise ValueError("msgpack data is truncated")
138
+ position += length
139
+ return data[position - length : position]
140
+
141
+ def number(fmt: str) -> Any:
142
+ return struct.unpack(fmt, take(struct.calcsize(fmt)))[0]
143
+
144
+ def text(length: int) -> str:
145
+ try:
146
+ return take(length).decode()
147
+ except UnicodeDecodeError:
148
+ raise ValueError("msgpack data has a str which is not UTF-8") from None
149
+
150
+ def mapping(length: int) -> dict[Any, Any]:
151
+ items = {}
152
+ for _ in range(length):
153
+ key = value()
154
+ try:
155
+ duplicate = key in items
156
+ except TypeError:
157
+ raise ValueError(
158
+ "msgpack data has a map keyed by an array or a map"
159
+ ) from None
160
+ if duplicate:
161
+ raise ValueError(f"msgpack data has a map with the key {key!r} twice")
162
+ items[key] = value()
163
+ return items
164
+
165
+ def value() -> Any:
166
+ first = take(1)[0]
167
+ if first < 0x80:
168
+ return first
169
+ if first >= 0xE0:
170
+ return first - 0x100
171
+ if first < 0x90:
172
+ return mapping(first & 0x0F)
173
+ if first < 0xA0:
174
+ return [value() for _ in range(first & 0x0F)]
175
+ if first < 0xC0:
176
+ return text(first & 0x1F)
177
+ if first == 0xC0:
178
+ return None
179
+ if first in (0xC2, 0xC3):
180
+ return first == 0xC3
181
+ if first in _NUMBERS:
182
+ return number(_NUMBERS[first])
183
+ if first in _FIXED_EXT.values():
184
+ code = number(">b")
185
+ return Ext(code, take(1 << (first - 0xD4)))
186
+ if first not in _LENGTHS:
187
+ raise ValueError(f"msgpack data has the unused byte {first:#x}")
188
+
189
+ length = number(_LENGTHS[first])
190
+ if first <= 0xC6:
191
+ return take(length)
192
+ if first <= 0xC9:
193
+ code = number(">b")
194
+ return Ext(code, take(length))
195
+ if first <= 0xDB:
196
+ return text(length)
197
+ if first <= 0xDD:
198
+ return [value() for _ in range(length)]
199
+ return mapping(length)
200
+
201
+ try:
202
+ result = value()
203
+ except RecursionError:
204
+ raise ValueError("msgpack data is too deeply nested") from None
205
+ if position != len(data):
206
+ raise ValueError("msgpack data has more than one value")
207
+ return result
@@ -0,0 +1,234 @@
1
+ """The @native decorator, marking a dataclass as part of the schema and binding it to its native equivalent"""
2
+
3
+ import inspect
4
+ import sys
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, fields, is_dataclass
7
+ from functools import wraps
8
+ from types import FunctionType
9
+ from typing import Any, overload
10
+ from weakref import WeakKeyDictionary
11
+
12
+ from ._mode import Mode, _fix_mode
13
+
14
+
15
+ class NativeBindingError(RuntimeError):
16
+ """A @native class has no native binding available"""
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class NativeInfo:
21
+ tag: str
22
+ """Names the type when serialised, e.g. in unions: stable across languages, so not tied to Python's layout"""
23
+
24
+
25
+ _registry: WeakKeyDictionary[type, NativeInfo] = WeakKeyDictionary()
26
+
27
+
28
+ @overload
29
+ def native[C: type](cls: C, /) -> C: ...
30
+
31
+
32
+ @overload
33
+ def native[C: type](*, tag: str | None = None) -> Callable[[C], C]: ...
34
+
35
+
36
+ def native(cls: Any = None, /, *, tag: str | None = None) -> Any:
37
+ """
38
+ Marks a frozen dataclass as part of the schema, for which native code is generated.
39
+
40
+ Apply above @dataclass. The class's fields are stored in its native equivalent. If that is not available, strict
41
+ mode (the default) raises when the class is instantiated, and mixed mode leaves it a plain dataclass. In pure mode
42
+ (DATACLASS_NATIVE_MODE=pure), the class is returned unchanged.
43
+
44
+ :param tag: Names the type when serialised. Defaults to the module and qualified name: set it to keep the wire
45
+ format when moving or renaming the class
46
+ """
47
+
48
+ def decorate(cls: type) -> type:
49
+ _validate(cls)
50
+ _registry[cls] = NativeInfo(tag=tag or f"{cls.__module__}.{cls.__qualname__}")
51
+ _compare_arrays(cls)
52
+ if (mode := _fix_mode()) is not Mode.PURE:
53
+ _install_binding(cls, required=mode is Mode.STRICT)
54
+ return cls
55
+
56
+ return decorate if cls is None else decorate(cls)
57
+
58
+
59
+ def native_function[F: Callable[..., Any]](module: str) -> Callable[[F], F]:
60
+ """
61
+ Marks a function as implemented natively, by the function of its name in an extension module.
62
+
63
+ Its @native arguments are given to the native function as their native objects, and what that returns becomes the
64
+ object of the return annotation, neither being copied. The function's body is its Python implementation: called
65
+ in pure mode, and in mixed mode if the native function, or the binding of a class it uses, is not available.
66
+ Strict mode (the default) then raises, when the function is first called.
67
+
68
+ :param module: The extension module: relative to the function's package if it starts with a dot, e.g. "._pricing"
69
+ """
70
+
71
+ def decorate(fn: Any) -> Any:
72
+ if not isinstance(fn, FunctionType):
73
+ raise TypeError(
74
+ f"@native_function must be applied to a function, not to {fn!r}"
75
+ )
76
+ code = fn.__code__
77
+ if code.co_kwonlyargcount or code.co_flags & (
78
+ inspect.CO_VARARGS | inspect.CO_VARKEYWORDS
79
+ ):
80
+ raise TypeError(
81
+ f"{fn.__qualname__}: keyword-only parameters, *args and **kwargs are not supported"
82
+ )
83
+
84
+ if (mode := _fix_mode()) is Mode.PURE:
85
+ return fn
86
+
87
+ # Once first called: what to call
88
+ bound: list[Callable[..., Any]] = []
89
+
90
+ @wraps(fn)
91
+ def call(*args: Any, **kwargs: Any) -> Any:
92
+ if not bound:
93
+ # Lazily, as classes are bound: the function's module imports without the extension
94
+ from ._runtime import bind_function
95
+
96
+ bound.append(bind_function(fn, module, required=mode is Mode.STRICT))
97
+ return bound[0](*args, **kwargs)
98
+
99
+ return call
100
+
101
+ return decorate
102
+
103
+
104
+ def extension_name(module: str) -> str:
105
+ """The extension module holding the native classes of a schema module: pkg._mod_native for pkg.mod"""
106
+ package, _, name = module.rpartition(".")
107
+ return f"{package}{'.' if package else ''}_{name}_native"
108
+
109
+
110
+ def is_native(cls: type) -> bool:
111
+ """Whether the class itself, not just a base, is decorated with @native"""
112
+ return cls in _registry
113
+
114
+
115
+ def native_info(cls: type) -> NativeInfo:
116
+ try:
117
+ return _registry[cls]
118
+ except KeyError:
119
+ raise TypeError(f"{cls.__qualname__} is not decorated with @native") from None
120
+
121
+
122
+ def _validate(cls: Any):
123
+ if hasattr(cls, "model_fields"):
124
+ raise TypeError(
125
+ f"{cls.__qualname__}: pydantic models are not supported: use pydantic.dataclasses.dataclass"
126
+ )
127
+
128
+ if not isinstance(cls, type) or not is_dataclass(cls):
129
+ raise TypeError(
130
+ f"@native must be applied to a dataclass, above @dataclass, not to {cls!r}"
131
+ )
132
+
133
+ if "__slots__" in vars(cls):
134
+ raise TypeError(
135
+ f"{cls.__qualname__}: dataclasses with slots are not supported, as fields are stored natively"
136
+ )
137
+
138
+ if getattr(cls, "__type_params__", ()) or getattr(cls, "__parameters__", ()):
139
+ raise TypeError(f"{cls.__qualname__}: generic dataclasses are not supported")
140
+
141
+
142
+ def _compare_arrays(cls: Any):
143
+ """
144
+ Gives a class with fields which are arrays an __eq__ and __hash__ which compare them by what they hold, as the
145
+ dataclass's own compare each field with ==, which of arrays gives an array. Arrays are equal which hold the same
146
+ bits: so one of NaN equals itself, and 0.0 is not -0.0
147
+ """
148
+ np = sys.modules.get("numpy")
149
+ if np is None or not cls.__dataclass_params__.eq:
150
+ return
151
+
152
+ # Here, as introspect imports this module
153
+ from . import schema as s
154
+ from .introspect import resolve
155
+
156
+ arrays = set()
157
+ for f in fields(cls):
158
+ try:
159
+ # Each alone, as others may name classes which are not yet defined
160
+ tp = (
161
+ eval(f.type, dict(vars(sys.modules[cls.__module__])))
162
+ if isinstance(f.type, str)
163
+ else f.type
164
+ )
165
+ t = resolve(tp, f.name)
166
+ except (NameError, AttributeError, KeyError, SyntaxError, TypeError):
167
+ continue
168
+ if isinstance(t.inner if isinstance(t, s.Optional) else t, s.Array):
169
+ arrays.add(f.name)
170
+ if not arrays:
171
+ return
172
+
173
+ names = [f.name for f in fields(cls) if f.compare]
174
+
175
+ def bits(value: Any) -> Any:
176
+ if isinstance(value, np.ndarray):
177
+ return value.dtype.str, value.shape, value.tobytes()
178
+ return value
179
+
180
+ def key(self: Any) -> tuple[Any, ...]:
181
+ values = ((name, getattr(self, name)) for name in names)
182
+ return tuple(bits(value) if name in arrays else value for name, value in values)
183
+
184
+ def __eq__(self: Any, other: Any) -> Any:
185
+ return (
186
+ key(self) == key(other)
187
+ if other.__class__ is self.__class__
188
+ else NotImplemented
189
+ )
190
+
191
+ def __hash__(self: Any) -> int:
192
+ return hash(key(self))
193
+
194
+ cls.__eq__ = __eq__
195
+ if cls.__dataclass_params__.frozen:
196
+ # One which is not has none, as its fields may be set
197
+ cls.__hash__ = __hash__
198
+
199
+
200
+ def _install_binding(cls: type, required: bool):
201
+ # Once bound: the native class, or None if it has none (mixed mode)
202
+ native: list[type | None] = []
203
+
204
+ def bound() -> type | None:
205
+ if not native:
206
+ # Lazily, so that schema modules import without their extension, and before all their classes exist
207
+ from ._runtime import bind
208
+
209
+ native.append(bind(cls, required))
210
+ return native[0]
211
+
212
+ def __new__(klass: type, *_args: Any, **_kwargs: Any) -> Any:
213
+ if not is_native(klass):
214
+ raise TypeError(
215
+ f"{klass.__qualname__} derives from @native {cls.__qualname__}, so must be decorated with @native"
216
+ )
217
+
218
+ self = object.__new__(klass)
219
+ if (native_class := bound()) is not None:
220
+ self.__dict__["__native__"] = native_class()
221
+ return self
222
+
223
+ def _from_native(klass: type, handle: Any) -> Any:
224
+ """An instance holding the given native object, e.g. one returned by C++, without copying it"""
225
+ if klass is not cls or type(handle) is not bound():
226
+ raise TypeError(
227
+ f"{handle!r} is not the native object of a {klass.__qualname__}"
228
+ )
229
+ self = object.__new__(klass)
230
+ self.__dict__["__native__"] = handle
231
+ return self
232
+
233
+ cls.__new__ = staticmethod(__new__) # pyright: ignore[reportAttributeAccessIssue]
234
+ cls._from_native = classmethod(_from_native) # pyright: ignore[reportAttributeAccessIssue]