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.
- dataclass_native/__init__.py +60 -0
- dataclass_native/__main__.py +5 -0
- dataclass_native/_arrow.py +822 -0
- dataclass_native/_json.py +783 -0
- dataclass_native/_mode.py +57 -0
- dataclass_native/_msgpack.py +207 -0
- dataclass_native/_native.py +234 -0
- dataclass_native/_runtime.py +607 -0
- dataclass_native/_version.py +24 -0
- dataclass_native/_wire.py +901 -0
- dataclass_native/arrays.py +13 -0
- dataclass_native/backends/__init__.py +0 -0
- dataclass_native/backends/bindings.py +74 -0
- dataclass_native/backends/cpp.py +574 -0
- dataclass_native/backends/templates/bindings.cpp.j2 +58 -0
- dataclass_native/backends/templates/extensions.cmake.j2 +12 -0
- dataclass_native/backends/templates/header.hpp.j2 +75 -0
- dataclass_native/cli.py +125 -0
- dataclass_native/cmake/dataclass_native-config.cmake +67 -0
- dataclass_native/include/dataclass_native/arrow.hpp +2022 -0
- dataclass_native/include/dataclass_native/json.hpp +1903 -0
- dataclass_native/include/dataclass_native/msgpack.hpp +1513 -0
- dataclass_native/include/dataclass_native/python.hpp +594 -0
- dataclass_native/include/dataclass_native/reflect.hpp +63 -0
- dataclass_native/include/dataclass_native/types.hpp +417 -0
- dataclass_native/introspect.py +811 -0
- dataclass_native/py.typed +0 -0
- dataclass_native/schema.py +553 -0
- dataclass_native/types.py +103 -0
- dataclass_native-1.0.0.dist-info/METADATA +339 -0
- dataclass_native-1.0.0.dist-info/RECORD +35 -0
- dataclass_native-1.0.0.dist-info/WHEEL +5 -0
- dataclass_native-1.0.0.dist-info/entry_points.txt +2 -0
- dataclass_native-1.0.0.dist-info/licenses/LICENSE +21 -0
- dataclass_native-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Binds @native classes to their native classes, those of their module's extension (see backends.bindings).
|
|
3
|
+
|
|
4
|
+
A bound class's instances hold a native object, their handle, as __native__. Its fields are descriptors which get and
|
|
5
|
+
set the handle's members, converting between Python values and those of the extension: the handles of @native
|
|
6
|
+
classes, the extension's enums, and lists, sets and dicts.
|
|
7
|
+
|
|
8
|
+
A function marked with @native_function is bound likewise, to the function of its name in a hand-written extension:
|
|
9
|
+
its arguments, and what it returns, are converted as fields are.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import datetime as dt
|
|
13
|
+
import decimal
|
|
14
|
+
import inspect
|
|
15
|
+
import uuid
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from copyreg import __newobj__ # pyright: ignore[reportAttributeAccessIssue]
|
|
18
|
+
from dataclasses import MISSING, fields
|
|
19
|
+
from enum import Enum
|
|
20
|
+
from functools import wraps
|
|
21
|
+
from importlib import import_module
|
|
22
|
+
from importlib.util import resolve_name
|
|
23
|
+
from threading import RLock
|
|
24
|
+
from types import ModuleType, NoneType
|
|
25
|
+
from typing import Any, get_type_hints
|
|
26
|
+
from weakref import WeakValueDictionary
|
|
27
|
+
|
|
28
|
+
from . import schema as s
|
|
29
|
+
from ._mode import ENV_VAR, Mode
|
|
30
|
+
from ._native import NativeBindingError, extension_name
|
|
31
|
+
from .introspect import describe, resolve
|
|
32
|
+
|
|
33
|
+
HANDLE = "__native__"
|
|
34
|
+
|
|
35
|
+
# Converts a value, or None if it is used as it is
|
|
36
|
+
type _Converter = Callable[[Any], Any] | None
|
|
37
|
+
|
|
38
|
+
_SCALARS: dict[type, type] = {
|
|
39
|
+
s.Bool: bool,
|
|
40
|
+
s.Int: int,
|
|
41
|
+
s.Float: float,
|
|
42
|
+
s.Str: str,
|
|
43
|
+
s.Bytes: bytes,
|
|
44
|
+
s.Date: dt.date,
|
|
45
|
+
s.Time: dt.time,
|
|
46
|
+
s.DateTime: dt.datetime,
|
|
47
|
+
s.NaiveDateTime: dt.datetime,
|
|
48
|
+
s.TimeDelta: dt.timedelta,
|
|
49
|
+
s.Uuid: uuid.UUID,
|
|
50
|
+
s.Decimal: decimal.Decimal,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# A sequence of these is natively bytes, as in C++ both are a vector of them
|
|
54
|
+
_BYTE = s.Int(8, signed=False)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _Missing(Exception):
|
|
58
|
+
"""A class has no native class: in mixed mode, it is then a plain dataclass"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Binding:
|
|
62
|
+
def __init__(self, cls: type, native: type):
|
|
63
|
+
self.cls = cls
|
|
64
|
+
self.native = native
|
|
65
|
+
self.fields: dict[str, tuple[_Converter, _Converter]] = {}
|
|
66
|
+
"""By name, the converters to and from the native value"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_lock = RLock()
|
|
70
|
+
# None for a class found to have no native class
|
|
71
|
+
_bindings: dict[type, _Binding | None] = {}
|
|
72
|
+
_enums: dict[type[Enum], type] = {}
|
|
73
|
+
# Being bound: installed together, as they may refer to each other
|
|
74
|
+
_pending: list[_Binding] = []
|
|
75
|
+
# The Python objects of the handles which have been shared, so that a Shared field gives the object it was given
|
|
76
|
+
_shared: WeakValueDictionary[int, Any] = WeakValueDictionary()
|
|
77
|
+
|
|
78
|
+
_REMEDY = (
|
|
79
|
+
f"Build its extension, or set {ENV_VAR} to {Mode.MIXED.value} or {Mode.PURE.value}"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def bind(cls: type, required: bool) -> type | None:
|
|
84
|
+
"""
|
|
85
|
+
The native class of a @native class, binding the class to it if it has not been.
|
|
86
|
+
|
|
87
|
+
:param required: Raise if it has no native class, rather than return None
|
|
88
|
+
"""
|
|
89
|
+
with _lock:
|
|
90
|
+
try:
|
|
91
|
+
return _installing(lambda: _binding(cls)).native
|
|
92
|
+
except _Missing as e:
|
|
93
|
+
if required:
|
|
94
|
+
raise NativeBindingError(
|
|
95
|
+
f"No native binding is available for {cls.__module__}.{cls.__qualname__}: {e}. {_REMEDY}"
|
|
96
|
+
) from None
|
|
97
|
+
_bindings[cls] = None
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def bind_function(
|
|
102
|
+
fn: Callable[..., Any], module: str, required: bool
|
|
103
|
+
) -> Callable[..., Any]:
|
|
104
|
+
"""
|
|
105
|
+
What to call for a function marked with @native_function: one which calls the function of its name in the
|
|
106
|
+
extension module, converting its arguments and what that returns.
|
|
107
|
+
|
|
108
|
+
:param required: Raise if it has no native function, or a class it uses has no native class, rather than return fn
|
|
109
|
+
"""
|
|
110
|
+
name = f"{fn.__module__}.{fn.__qualname__}"
|
|
111
|
+
signature = inspect.signature(fn)
|
|
112
|
+
parameters = list(signature.parameters)
|
|
113
|
+
hints = get_type_hints(fn, include_extras=True)
|
|
114
|
+
if unannotated := [p for p in (*parameters, "return") if p not in hints]:
|
|
115
|
+
raise TypeError(f"{name}: {', '.join(unannotated)} must be annotated")
|
|
116
|
+
|
|
117
|
+
def make() -> tuple[Callable[..., Any], list[_Converter], _Converter]:
|
|
118
|
+
extension = _import(resolve_name(module, fn.__module__.rpartition(".")[0]))
|
|
119
|
+
try:
|
|
120
|
+
native = getattr(extension, fn.__name__)
|
|
121
|
+
except AttributeError:
|
|
122
|
+
raise _Missing(f"{extension.__name__} has no {fn.__name__}") from None
|
|
123
|
+
returns = hints["return"]
|
|
124
|
+
return (
|
|
125
|
+
native,
|
|
126
|
+
[_to_native(resolve(hints[p], f"{name}({p})")) for p in parameters],
|
|
127
|
+
None if returns is NoneType else _from_native(resolve(returns, name)),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
native, to_native, from_native = _installing(make)
|
|
132
|
+
except _Missing as e:
|
|
133
|
+
if required:
|
|
134
|
+
raise NativeBindingError(
|
|
135
|
+
f"No native function is available for {name}: {e}. {_REMEDY}"
|
|
136
|
+
) from None
|
|
137
|
+
return fn
|
|
138
|
+
|
|
139
|
+
def call(*args: Any, **kwargs: Any) -> Any:
|
|
140
|
+
if kwargs or len(args) != len(parameters):
|
|
141
|
+
arguments = signature.bind(*args, **kwargs)
|
|
142
|
+
arguments.apply_defaults()
|
|
143
|
+
args = arguments.args
|
|
144
|
+
|
|
145
|
+
converted = []
|
|
146
|
+
for parameter, convert, value in zip(parameters, to_native, args):
|
|
147
|
+
try:
|
|
148
|
+
converted.append(convert(value) if convert else value)
|
|
149
|
+
except (TypeError, ValueError):
|
|
150
|
+
raise TypeError(f"{name}: {parameter} cannot be {value!r}") from None
|
|
151
|
+
|
|
152
|
+
result = native(*converted)
|
|
153
|
+
return from_native(result) if from_native else result
|
|
154
|
+
|
|
155
|
+
return call
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _installing[T](make: Callable[[], T]) -> T:
|
|
159
|
+
"""What make returns, having installed the classes which it bound: or, if it raises, having unbound them"""
|
|
160
|
+
with _lock:
|
|
161
|
+
try:
|
|
162
|
+
made = make()
|
|
163
|
+
for pending in _pending:
|
|
164
|
+
_install(pending)
|
|
165
|
+
return made
|
|
166
|
+
except BaseException:
|
|
167
|
+
for pending in _pending:
|
|
168
|
+
del _bindings[pending.cls]
|
|
169
|
+
raise
|
|
170
|
+
finally:
|
|
171
|
+
_pending.clear()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def native_object(obj: Any) -> Any:
|
|
175
|
+
"""The native object of an instance of a bound class"""
|
|
176
|
+
try:
|
|
177
|
+
return obj.__dict__[HANDLE]
|
|
178
|
+
except KeyError:
|
|
179
|
+
# Made by pydantic
|
|
180
|
+
return _adopt(obj)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def wrap(cls: type, handle: Any) -> Any:
|
|
184
|
+
"""An instance of a bound class, holding the given native object"""
|
|
185
|
+
obj = object.__new__(cls)
|
|
186
|
+
obj.__dict__[HANDLE] = handle
|
|
187
|
+
return obj
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _binding(cls: type) -> _Binding:
|
|
191
|
+
try:
|
|
192
|
+
binding = _bindings[cls]
|
|
193
|
+
except KeyError:
|
|
194
|
+
pass
|
|
195
|
+
else:
|
|
196
|
+
if binding is None:
|
|
197
|
+
raise _Missing(f"{cls.__qualname__} has none")
|
|
198
|
+
return binding
|
|
199
|
+
|
|
200
|
+
if cls.__qualname__ != cls.__name__:
|
|
201
|
+
raise _Missing("only the classes at the top level of a module have one")
|
|
202
|
+
|
|
203
|
+
struct = describe(cls)
|
|
204
|
+
assert isinstance(struct, s.Struct)
|
|
205
|
+
binding = _bindings[cls] = _Binding(cls, _native_type(struct))
|
|
206
|
+
_pending.append(binding)
|
|
207
|
+
for f in struct.fields:
|
|
208
|
+
binding.fields[f.name] = _to_native(f.type), _from_native(f.type)
|
|
209
|
+
return binding
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _extension(module: str) -> ModuleType:
|
|
213
|
+
return _import(extension_name(module))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _import(name: str) -> ModuleType:
|
|
217
|
+
"""An extension module, which may be missing"""
|
|
218
|
+
try:
|
|
219
|
+
return import_module(name)
|
|
220
|
+
except ModuleNotFoundError as e:
|
|
221
|
+
# Not, e.g., a module which the extension itself imports
|
|
222
|
+
if e.name != name and not name.startswith(f"{e.name}."):
|
|
223
|
+
raise
|
|
224
|
+
raise _Missing(f"there is no extension module {name}") from None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _native_type(item: s.Struct | s.Enum) -> type:
|
|
228
|
+
"""The native class of a struct or enum, checked to have been generated from this version of it"""
|
|
229
|
+
extension = _extension(item.module)
|
|
230
|
+
generated = extension.__schema__.get(item.name)
|
|
231
|
+
if generated is None:
|
|
232
|
+
raise _Missing(f"{extension.__name__} was built without {item.name}")
|
|
233
|
+
if generated != s.schema_hash(item):
|
|
234
|
+
raise NativeBindingError(
|
|
235
|
+
f"{item.module}.{item.name} has changed since {extension.__name__} was built: build it again"
|
|
236
|
+
)
|
|
237
|
+
return getattr(extension, item.name)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _native_enum(ref: s.EnumRef) -> type:
|
|
241
|
+
try:
|
|
242
|
+
return _enums[ref.cls]
|
|
243
|
+
except KeyError:
|
|
244
|
+
enum = describe(ref.cls)
|
|
245
|
+
assert isinstance(enum, s.Enum)
|
|
246
|
+
native = _enums[ref.cls] = _native_type(enum)
|
|
247
|
+
return native
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _struct_class(t: s.Type) -> type | None:
|
|
251
|
+
"""The @native class of a struct, however it is held"""
|
|
252
|
+
match t:
|
|
253
|
+
case (
|
|
254
|
+
s.StructRef(cls=cls)
|
|
255
|
+
| s.Shared(s.StructRef(cls=cls))
|
|
256
|
+
| s.Indirect(s.StructRef(cls=cls))
|
|
257
|
+
):
|
|
258
|
+
return cls
|
|
259
|
+
case _:
|
|
260
|
+
return None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _error(value: Any, expected: str) -> TypeError:
|
|
264
|
+
return TypeError(f"{value!r} is not {expected}")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _by_reference(t: s.Type) -> bool:
|
|
268
|
+
"""Whether a struct is held by reference, so that reading it gives the object it was given: if Shared or mutable"""
|
|
269
|
+
return isinstance(t, s.Shared) or (isinstance(t, s.StructRef) and t.mutable)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _to_native(t: s.Type) -> _Converter:
|
|
273
|
+
"""Converts a Python value of a type to that its native member is set to, checking what nanobind would not"""
|
|
274
|
+
if cls := _struct_class(t):
|
|
275
|
+
_binding(cls)
|
|
276
|
+
|
|
277
|
+
def handle(value: Any) -> Any:
|
|
278
|
+
# Exactly, as a subclass has a native class of its own
|
|
279
|
+
if type(value) is not cls:
|
|
280
|
+
raise _error(value, f"a {cls.__qualname__}")
|
|
281
|
+
try:
|
|
282
|
+
return value.__dict__[HANDLE]
|
|
283
|
+
except KeyError:
|
|
284
|
+
return _adopt(value)
|
|
285
|
+
|
|
286
|
+
def share(value: Any) -> Any:
|
|
287
|
+
shared = handle(value)
|
|
288
|
+
_shared[id(shared)] = value
|
|
289
|
+
return shared
|
|
290
|
+
|
|
291
|
+
return share if _by_reference(t) else handle
|
|
292
|
+
|
|
293
|
+
match t:
|
|
294
|
+
case s.EnumRef(cls=enum):
|
|
295
|
+
native = _native_enum(t)
|
|
296
|
+
members = {
|
|
297
|
+
value: getattr(native, member.name)
|
|
298
|
+
for value, member in s.enum_members(enum).items()
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
def member(value: Any) -> Any:
|
|
302
|
+
try:
|
|
303
|
+
return members[value]
|
|
304
|
+
except (KeyError, TypeError):
|
|
305
|
+
raise _error(value, f"a {enum.__qualname__}") from None
|
|
306
|
+
|
|
307
|
+
return member
|
|
308
|
+
|
|
309
|
+
case s.Optional(inner):
|
|
310
|
+
convert = _to_native(inner)
|
|
311
|
+
return convert and (lambda value: None if value is None else convert(value))
|
|
312
|
+
|
|
313
|
+
case s.Sequence(element):
|
|
314
|
+
convert = bytes if element == _BYTE else _each(_to_native(element), list)
|
|
315
|
+
|
|
316
|
+
def sequence(value: Any) -> Any:
|
|
317
|
+
if type(value) is not tuple:
|
|
318
|
+
raise _error(value, "a tuple")
|
|
319
|
+
return convert(value) if convert else value
|
|
320
|
+
|
|
321
|
+
return sequence
|
|
322
|
+
|
|
323
|
+
case s.Array():
|
|
324
|
+
np = import_module("numpy")
|
|
325
|
+
dtype = np.dtype(t.dtype)
|
|
326
|
+
of = (
|
|
327
|
+
f"of {t.dimensions} dimensions"
|
|
328
|
+
if t.dimensions > 1
|
|
329
|
+
else "of one dimension"
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def array(value: Any) -> Any:
|
|
333
|
+
if (
|
|
334
|
+
type(value) is not np.ndarray
|
|
335
|
+
or value.dtype != dtype
|
|
336
|
+
or value.ndim != t.dimensions
|
|
337
|
+
):
|
|
338
|
+
raise _error(value, f"an array of {dtype}, {of}")
|
|
339
|
+
# As it is in memory, which is what the native array copies
|
|
340
|
+
return np.ascontiguousarray(value)
|
|
341
|
+
|
|
342
|
+
return array
|
|
343
|
+
|
|
344
|
+
case s.Tuple(elements):
|
|
345
|
+
convert = _zipped([_to_native(e) for e in elements])
|
|
346
|
+
|
|
347
|
+
def fixed(value: Any) -> Any:
|
|
348
|
+
if type(value) is not tuple or len(value) != len(elements):
|
|
349
|
+
raise _error(value, f"a tuple of {len(elements)}")
|
|
350
|
+
return convert(value) if convert else value
|
|
351
|
+
|
|
352
|
+
return fixed
|
|
353
|
+
|
|
354
|
+
case s.Set(element):
|
|
355
|
+
convert = _each(_to_native(element), set)
|
|
356
|
+
|
|
357
|
+
def set_(value: Any) -> Any:
|
|
358
|
+
if type(value) is not frozenset:
|
|
359
|
+
raise _error(value, "a frozenset")
|
|
360
|
+
return convert(value) if convert else value
|
|
361
|
+
|
|
362
|
+
return set_
|
|
363
|
+
|
|
364
|
+
case s.Map(key, value_type):
|
|
365
|
+
convert = _items(_to_native(key), _to_native(value_type)) or dict
|
|
366
|
+
|
|
367
|
+
def mapping(value: Any) -> Any:
|
|
368
|
+
if not isinstance(value, Mapping):
|
|
369
|
+
raise _error(value, "a Mapping")
|
|
370
|
+
return convert(value)
|
|
371
|
+
|
|
372
|
+
return mapping
|
|
373
|
+
|
|
374
|
+
case s.Union(members):
|
|
375
|
+
converters: dict[type, _Converter] = {}
|
|
376
|
+
for m in members:
|
|
377
|
+
converters.setdefault(_python_type(m), _to_native(m))
|
|
378
|
+
if any(isinstance(m, s.Float) for m in members):
|
|
379
|
+
converters.setdefault(int, None)
|
|
380
|
+
expected = " or ".join(typ.__name__ for typ in converters)
|
|
381
|
+
|
|
382
|
+
def union(value: Any) -> Any:
|
|
383
|
+
typ = type(value)
|
|
384
|
+
if typ not in converters and isinstance(value, Mapping):
|
|
385
|
+
typ = Mapping
|
|
386
|
+
try:
|
|
387
|
+
convert = converters[typ]
|
|
388
|
+
except KeyError:
|
|
389
|
+
raise _error(value, expected) from None
|
|
390
|
+
return convert(value) if convert else value
|
|
391
|
+
|
|
392
|
+
return union
|
|
393
|
+
|
|
394
|
+
case _:
|
|
395
|
+
return None
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _from_native(t: s.Type) -> _Converter:
|
|
399
|
+
"""Converts the value of a native member to the Python value of its type"""
|
|
400
|
+
if cls := _struct_class(t):
|
|
401
|
+
if not _by_reference(t):
|
|
402
|
+
return lambda handle: wrap(cls, handle)
|
|
403
|
+
|
|
404
|
+
def shared(handle: Any) -> Any:
|
|
405
|
+
try:
|
|
406
|
+
return _shared[id(handle)]
|
|
407
|
+
except KeyError:
|
|
408
|
+
obj = _shared[id(handle)] = wrap(cls, handle)
|
|
409
|
+
return obj
|
|
410
|
+
|
|
411
|
+
return shared
|
|
412
|
+
|
|
413
|
+
match t:
|
|
414
|
+
case s.EnumRef(cls=enum):
|
|
415
|
+
native = _native_enum(t)
|
|
416
|
+
return {getattr(native, member.name): member for member in enum}.__getitem__
|
|
417
|
+
case s.Optional(inner):
|
|
418
|
+
convert = _from_native(inner)
|
|
419
|
+
return convert and (lambda value: None if value is None else convert(value))
|
|
420
|
+
case s.Sequence(element):
|
|
421
|
+
return (
|
|
422
|
+
tuple
|
|
423
|
+
if element == _BYTE
|
|
424
|
+
else _each(_from_native(element), tuple) or tuple
|
|
425
|
+
)
|
|
426
|
+
case s.Tuple(elements):
|
|
427
|
+
return _zipped([_from_native(e) for e in elements])
|
|
428
|
+
case s.Set(element):
|
|
429
|
+
return _each(_from_native(element), frozenset) or frozenset
|
|
430
|
+
case s.Map(key, value_type):
|
|
431
|
+
return _items(_from_native(key), _from_native(value_type))
|
|
432
|
+
case s.Union(members):
|
|
433
|
+
converters = {_native_value_type(m): _from_native(m) for m in members}
|
|
434
|
+
if not any(converters.values()):
|
|
435
|
+
return None
|
|
436
|
+
|
|
437
|
+
def union(value: Any) -> Any:
|
|
438
|
+
convert = converters[type(value)]
|
|
439
|
+
return convert(value) if convert else value
|
|
440
|
+
|
|
441
|
+
return union
|
|
442
|
+
case _:
|
|
443
|
+
return None
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _each(convert: _Converter, container: Callable[[Any], Any]) -> _Converter:
|
|
447
|
+
return convert and (lambda values: container(map(convert, values)))
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _zipped(converters: list[_Converter]) -> _Converter:
|
|
451
|
+
if not any(converters):
|
|
452
|
+
return None
|
|
453
|
+
return lambda values: tuple(
|
|
454
|
+
c(v) if c else v for c, v in zip(converters, values, strict=True)
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _items(key: _Converter, value: _Converter) -> _Converter:
|
|
459
|
+
if not key and not value:
|
|
460
|
+
return None
|
|
461
|
+
return lambda items: {
|
|
462
|
+
(key(k) if key else k): (value(v) if value else v) for k, v in items.items()
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _python_type(t: s.Type) -> type:
|
|
467
|
+
"""The type of the Python values of a union's member, which tells them from those of its other members"""
|
|
468
|
+
match t:
|
|
469
|
+
case s.EnumRef(cls=cls):
|
|
470
|
+
return cls
|
|
471
|
+
case s.Sequence() | s.Tuple():
|
|
472
|
+
return tuple
|
|
473
|
+
case s.Set():
|
|
474
|
+
return frozenset
|
|
475
|
+
case s.Map():
|
|
476
|
+
return Mapping
|
|
477
|
+
case _:
|
|
478
|
+
return _struct_class(t) or _SCALARS[type(t)]
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _native_value_type(t: s.Type) -> type:
|
|
482
|
+
"""As _python_type, of the member's native values"""
|
|
483
|
+
match t:
|
|
484
|
+
case s.EnumRef():
|
|
485
|
+
return _native_enum(t)
|
|
486
|
+
case s.Sequence(element):
|
|
487
|
+
return bytes if element == _BYTE else list
|
|
488
|
+
case s.Tuple():
|
|
489
|
+
return tuple
|
|
490
|
+
case s.Set():
|
|
491
|
+
return set
|
|
492
|
+
case s.Map():
|
|
493
|
+
return dict
|
|
494
|
+
case _:
|
|
495
|
+
cls = _struct_class(t)
|
|
496
|
+
return _binding(cls).native if cls else _SCALARS[type(t)]
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
class _Field:
|
|
500
|
+
"""A field of a bound class: gets and sets the member of the instance's native object"""
|
|
501
|
+
|
|
502
|
+
__slots__ = ("default", "from_native", "name", "to_native")
|
|
503
|
+
|
|
504
|
+
def __init__(
|
|
505
|
+
self, name: str, default: Any, to_native: _Converter, from_native: _Converter
|
|
506
|
+
):
|
|
507
|
+
self.name = name
|
|
508
|
+
self.default = default
|
|
509
|
+
self.to_native = to_native
|
|
510
|
+
self.from_native = from_native
|
|
511
|
+
|
|
512
|
+
def __get__(self, obj: Any, owner: type | None = None) -> Any:
|
|
513
|
+
if obj is None:
|
|
514
|
+
# As the dataclass's own attribute: its default, if any
|
|
515
|
+
if self.default is MISSING:
|
|
516
|
+
raise AttributeError(self.name)
|
|
517
|
+
return self.default
|
|
518
|
+
|
|
519
|
+
attributes = obj.__dict__
|
|
520
|
+
try:
|
|
521
|
+
handle = attributes[HANDLE]
|
|
522
|
+
except KeyError:
|
|
523
|
+
if _bindings.get(type(obj)) is not None:
|
|
524
|
+
handle = _adopt(obj)
|
|
525
|
+
else:
|
|
526
|
+
# Of a subclass which is not bound, so a plain dataclass
|
|
527
|
+
try:
|
|
528
|
+
return attributes[self.name]
|
|
529
|
+
except KeyError:
|
|
530
|
+
raise AttributeError(self.name) from None
|
|
531
|
+
|
|
532
|
+
value = getattr(handle, self.name)
|
|
533
|
+
return self.from_native(value) if self.from_native else value
|
|
534
|
+
|
|
535
|
+
def __set__(self, obj: Any, value: Any):
|
|
536
|
+
attributes = obj.__dict__
|
|
537
|
+
if HANDLE in attributes:
|
|
538
|
+
_set(attributes[HANDLE], obj, self.name, value, self.to_native)
|
|
539
|
+
else:
|
|
540
|
+
attributes[self.name] = value
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _set(handle: Any, obj: Any, name: str, value: Any, to_native: _Converter):
|
|
544
|
+
try:
|
|
545
|
+
setattr(handle, name, to_native(value) if to_native else value)
|
|
546
|
+
except (
|
|
547
|
+
TypeError,
|
|
548
|
+
ValueError,
|
|
549
|
+
): # A ValueError from bytes(), of ints which are not bytes
|
|
550
|
+
raise TypeError(
|
|
551
|
+
f"{type(obj).__qualname__}.{name} cannot be {value!r}"
|
|
552
|
+
) from None
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _adopt(obj: Any) -> Any:
|
|
556
|
+
"""
|
|
557
|
+
Gives an instance of a bound class a native object, holding the fields which are in its __dict__, and returns it.
|
|
558
|
+
Such is an instance made by pydantic, which sets an instance's __dict__ once it has validated its fields
|
|
559
|
+
"""
|
|
560
|
+
binding = _bindings[type(obj)]
|
|
561
|
+
assert binding is not None
|
|
562
|
+
attributes = obj.__dict__
|
|
563
|
+
handle = binding.native()
|
|
564
|
+
for name, (to_native, _) in binding.fields.items():
|
|
565
|
+
if name in attributes:
|
|
566
|
+
_set(handle, obj, name, attributes[name], to_native)
|
|
567
|
+
for name in binding.fields:
|
|
568
|
+
attributes.pop(name, None)
|
|
569
|
+
attributes[HANDLE] = handle
|
|
570
|
+
return handle
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _reduce(self: Any) -> tuple[Any, ...]:
|
|
574
|
+
"""As a plain dataclass pickles, so that a pickle made in one mode loads in any"""
|
|
575
|
+
return (
|
|
576
|
+
__newobj__,
|
|
577
|
+
(type(self),),
|
|
578
|
+
{f.name: getattr(self, f.name) for f in fields(self)},
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _setstate(self: Any, state: dict[str, Any]):
|
|
583
|
+
for name, value in state.items():
|
|
584
|
+
object.__setattr__(self, name, value)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _install(binding: _Binding):
|
|
588
|
+
cls = binding.cls
|
|
589
|
+
for f in fields(cls):
|
|
590
|
+
# The attribute the dataclass has is its default, if any
|
|
591
|
+
default = getattr(cls, f.name, MISSING)
|
|
592
|
+
setattr(cls, f.name, _Field(f.name, default, *binding.fields[f.name]))
|
|
593
|
+
# Else copying and pickling would copy the handle
|
|
594
|
+
cls.__reduce__ = _reduce # pyright: ignore[reportAttributeAccessIssue]
|
|
595
|
+
cls.__setstate__ = _setstate # pyright: ignore[reportAttributeAccessIssue]
|
|
596
|
+
|
|
597
|
+
if hasattr(cls, "__pydantic_validator__"):
|
|
598
|
+
init = cls.__init__
|
|
599
|
+
|
|
600
|
+
@wraps(init)
|
|
601
|
+
def __init__(self: Any, *args: Any, **kwargs: Any):
|
|
602
|
+
init(self, *args, **kwargs)
|
|
603
|
+
# Now, so that what the native class rejects is rejected here, not when a field is first read
|
|
604
|
+
if HANDLE not in self.__dict__:
|
|
605
|
+
_adopt(self)
|
|
606
|
+
|
|
607
|
+
cls.__init__ = __init__
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '1.0.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (1, 0, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|