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
File without changes
@@ -0,0 +1,553 @@
1
+ """
2
+ The schema model: a language-neutral description of the @native dataclasses and enums, from which each backend
3
+ generates code. Built by dataclass_native.introspect.
4
+ """
5
+
6
+ import datetime as dt
7
+ import decimal
8
+ import uuid
9
+ from collections.abc import Mapping
10
+ from contextlib import suppress
11
+ from dataclasses import dataclass, field, fields, is_dataclass, replace
12
+ from enum import Enum as PyEnum
13
+ from hashlib import sha256
14
+ from typing import Any
15
+
16
+
17
+ class SchemaError(TypeError):
18
+ """A class cannot be described by the schema"""
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Bool:
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Int:
28
+ bits: int = 64
29
+ signed: bool = True
30
+
31
+ @property
32
+ def min(self) -> int:
33
+ return -(2 ** (self.bits - 1)) if self.signed else 0
34
+
35
+ @property
36
+ def max(self) -> int:
37
+ return 2 ** (self.bits - 1) - 1 if self.signed else 2**self.bits - 1
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Float:
42
+ bits: int = 64
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Str:
47
+ pass
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Bytes:
52
+ pass
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Date:
57
+ pass
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Time:
62
+ """A time of day, without a timezone"""
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class DateTime:
67
+ """An instant: a timezone-aware datetime, stored as microseconds since the epoch, UTC"""
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class NaiveDateTime:
72
+ """A datetime with no timezone: a date and a time of day, stored as microseconds since 1970-01-01T00:00"""
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class TimeDelta:
77
+ pass
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Uuid:
82
+ """uuid.UUID: its 16 bytes"""
83
+
84
+
85
+ # The digits of the greatest Decimal: as many as a 64-bit integer holds of any value
86
+ DECIMAL_DIGITS = 18
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class Decimal:
91
+ """decimal.Decimal, of a fixed number of decimal places: stored as the integer which is that many places of it"""
92
+
93
+ places: int
94
+
95
+ def unscaled(self, value: decimal.Decimal) -> int:
96
+ """The integer a value is stored as. Raises ValueError unless it is that exactly, in no more than 18 digits"""
97
+ if not value.is_finite():
98
+ raise ValueError(f"{value} is not a number")
99
+ sign, digits, exponent = value.as_tuple()
100
+ assert isinstance(exponent, int)
101
+ number, shift = int("".join(map(str, digits))), exponent + self.places
102
+ if not number:
103
+ return 0
104
+ # Bounded first, as an exponent may be vast
105
+ if shift > DECIMAL_DIGITS or -shift > len(digits):
106
+ raise ValueError(f"{value} has not {self.places} decimal places")
107
+ number, rest = (
108
+ (number * 10**shift, 0) if shift >= 0 else divmod(number, 10**-shift)
109
+ )
110
+ if rest or number >= 10**DECIMAL_DIGITS:
111
+ raise ValueError(
112
+ f"{value} has not {self.places} decimal places, in {DECIMAL_DIGITS} digits"
113
+ )
114
+ return -number if sign else number
115
+
116
+ def value(self, unscaled: int) -> decimal.Decimal:
117
+ """The value which an integer is stored for: of exactly as many decimal places"""
118
+ digits = tuple(map(int, str(abs(unscaled))))
119
+ return decimal.Decimal((unscaled < 0, digits, -self.places))
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class EnumRef:
124
+ module: str
125
+ name: str
126
+ cls: type[PyEnum] = field(compare=False, repr=False)
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class StructRef:
131
+ module: str
132
+ name: str
133
+ cls: type = field(compare=False, repr=False)
134
+ mutable: bool = field(default=False, repr=False)
135
+ """Whether its class is not frozen: then it is held by reference, as Python holds it, not by value"""
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class Optional:
140
+ inner: "Type"
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Sequence:
145
+ """tuple[T, ...]"""
146
+
147
+ element: "Type"
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class Array:
152
+ """A numpy array of numbers, of a known number of dimensions, which is not copied when read"""
153
+
154
+ element: "Int | Float"
155
+ dimensions: int = 1
156
+ writeable: bool = field(default=False, repr=False)
157
+ """Whether it may be written to: as that of a class which is not frozen may"""
158
+
159
+ @property
160
+ def dtype(self) -> str:
161
+ """The name of the numpy dtype of its elements, e.g. float64"""
162
+ match self.element:
163
+ case Int(bits, signed):
164
+ return f"{'' if signed else 'u'}int{bits}"
165
+ case Float(bits):
166
+ return f"float{bits}"
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class Tuple:
171
+ """tuple[A, B, ...]: a fixed number of elements"""
172
+
173
+ elements: "tuple[Type, ...]"
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class Set:
178
+ """frozenset[T], of scalars or enums"""
179
+
180
+ element: "Type"
181
+
182
+
183
+ @dataclass(frozen=True)
184
+ class Map:
185
+ """Mapping[K, V], keyed by scalars or enums"""
186
+
187
+ key: "Type"
188
+ value: "Type"
189
+
190
+
191
+ @dataclass(frozen=True)
192
+ class Union:
193
+ """Two or more members, never Optional. Serialised with a tag if discriminated"""
194
+
195
+ members: "tuple[Type, ...]"
196
+ discriminated: bool = False
197
+
198
+
199
+ @dataclass(frozen=True)
200
+ class Shared:
201
+ """A value shared rather than copied, serialised by reference"""
202
+
203
+ target: StructRef
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class Indirect:
208
+ """
209
+ A struct held by value but stored out of line, as it is part of a recursive cycle of types. Inserted where needed
210
+ by introspection, so that all backends break cycles at the same fields
211
+ """
212
+
213
+ target: StructRef
214
+
215
+
216
+ type Scalar = (
217
+ Bool
218
+ | Int
219
+ | Float
220
+ | Str
221
+ | Bytes
222
+ | Date
223
+ | Time
224
+ | DateTime
225
+ | NaiveDateTime
226
+ | TimeDelta
227
+ | Uuid
228
+ | Decimal
229
+ )
230
+ type Type = (
231
+ Scalar
232
+ | EnumRef
233
+ | StructRef
234
+ | Optional
235
+ | Sequence
236
+ | Array
237
+ | Tuple
238
+ | Set
239
+ | Map
240
+ | Union
241
+ | Shared
242
+ | Indirect
243
+ )
244
+
245
+ SCALARS = (
246
+ Bool,
247
+ Int,
248
+ Float,
249
+ Str,
250
+ Bytes,
251
+ Date,
252
+ Time,
253
+ DateTime,
254
+ NaiveDateTime,
255
+ TimeDelta,
256
+ Uuid,
257
+ Decimal,
258
+ )
259
+
260
+
261
+ class _NoDefault:
262
+ def __repr__(self) -> str:
263
+ return "NO_DEFAULT"
264
+
265
+
266
+ NO_DEFAULT: Any = _NoDefault()
267
+
268
+
269
+ @dataclass(frozen=True)
270
+ class Field:
271
+ name: str
272
+ type: Type
273
+ default: Any = NO_DEFAULT
274
+ """A Python value conforming to type, from the field's default or default_factory"""
275
+
276
+ @property
277
+ def has_default(self) -> bool:
278
+ return self.default is not NO_DEFAULT
279
+
280
+
281
+ @dataclass(frozen=True)
282
+ class Struct:
283
+ module: str
284
+ name: str
285
+ tag: str
286
+ fields: tuple[Field, ...]
287
+ """All fields, including those inherited, in dataclass order"""
288
+ cls: type = field(compare=False, repr=False)
289
+ mutable: bool = False
290
+ """Whether its class is not frozen, so its fields may be set"""
291
+
292
+ @property
293
+ def ref(self) -> StructRef:
294
+ return StructRef(self.module, self.name, self.cls, self.mutable)
295
+
296
+
297
+ @dataclass(frozen=True)
298
+ class EnumMember:
299
+ name: str
300
+ value: int
301
+ """The Python value if an int, else the member's position"""
302
+ text: str = ""
303
+ """What it is written as in JSON: its Python value, if every member's is a str or an int, else its name"""
304
+ quoted: bool = True
305
+ """Whether that is written as a string"""
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class Enum:
310
+ module: str
311
+ name: str
312
+ tag: str
313
+ members: tuple[EnumMember, ...]
314
+ cls: type[PyEnum] = field(compare=False, repr=False)
315
+
316
+
317
+ @dataclass(frozen=True)
318
+ class Module:
319
+ name: str
320
+ enums: tuple[Enum, ...]
321
+ structs: tuple[Struct, ...]
322
+ """Ordered so that each struct follows those it holds by value"""
323
+ dependencies: tuple[str, ...]
324
+ """Other modules whose types this module's structs use"""
325
+
326
+
327
+ @dataclass(frozen=True)
328
+ class Schema:
329
+ modules: Mapping[str, Module]
330
+
331
+ def struct(self, ref: StructRef) -> Struct:
332
+ return next(s for s in self.modules[ref.module].structs if s.name == ref.name)
333
+
334
+ def enum(self, ref: EnumRef) -> Enum:
335
+ return next(e for e in self.modules[ref.module].enums if e.name == ref.name)
336
+
337
+
338
+ def _signature(t: Any) -> str:
339
+ """A type as text, the same whether or not introspection has made its recursive references Indirect"""
340
+ if isinstance(t, Indirect):
341
+ t = t.target
342
+ if isinstance(t, StructRef) and t.mutable:
343
+ return f"Mutable({_signature(replace(t, mutable=False))})"
344
+ if isinstance(t, tuple):
345
+ return f"({', '.join(map(_signature, t))})"
346
+ if not is_dataclass(t):
347
+ return repr(t)
348
+ args = ", ".join(_signature(getattr(t, f.name)) for f in fields(t) if f.repr)
349
+ return f"{type(t).__name__}({args})"
350
+
351
+
352
+ def schema_hash(item: Struct | Enum) -> str:
353
+ """
354
+ Identifies what code generated for a struct or enum depends on, so that code generated from another version of
355
+ it can be told. Not a struct's defaults: Python sets every field of the objects it makes
356
+ """
357
+ if isinstance(item, Struct):
358
+ lines = [f"{f.name}: {_signature(f.type)}" for f in item.fields]
359
+ else:
360
+ # With what it is in JSON, where that is not the number it is
361
+ lines = [
362
+ f"{m.name} = {m.value}"
363
+ + ("" if (m.text, m.quoted) == (str(m.value), False) else f" {m.text!r}")
364
+ for m in item.members
365
+ ]
366
+ if isinstance(item, Struct) and item.mutable:
367
+ lines.append("mutable")
368
+ return sha256("\n".join([item.tag, *lines]).encode()).hexdigest()[:16]
369
+
370
+
371
+ def is_key(t: Type) -> bool:
372
+ """Whether t may be a frozenset element or Mapping key: scalars and enums only"""
373
+ return isinstance(t, SCALARS + (EnumRef,))
374
+
375
+
376
+ def enum_members(cls: type[PyEnum]) -> dict[Any, PyEnum]:
377
+ """The member which each value given for an enum stands for: itself, or the member whose value it is"""
378
+ members: dict[Any, PyEnum] = {member: member for member in cls}
379
+ for member in cls:
380
+ with suppress(TypeError): # A value which cannot be hashed
381
+ members.setdefault(member.value, member)
382
+ return members
383
+
384
+
385
+ def json_values(cls: type[PyEnum]) -> dict[Any, PyEnum] | None:
386
+ """An enum's members by their values, if each is a str or an int and they differ as text: as JSON has them"""
387
+ values = [member.value for member in cls]
388
+ if all(type(v) in (str, int) for v in values) and len(set(map(str, values))) == len(
389
+ values
390
+ ):
391
+ return {member.value: member for member in cls}
392
+ return None
393
+
394
+
395
+ def json_kinds(t: Type) -> frozenset[str]:
396
+ """The kinds of JSON value a type is written as: of a string, also what form of one, if it has its own"""
397
+ match t:
398
+ case Bool():
399
+ return frozenset({"bool"})
400
+ case Int():
401
+ return frozenset({"int"})
402
+ case Float():
403
+ return frozenset({"float"})
404
+ case Str() | Bytes() | Sequence(Int(bits=8, signed=False)):
405
+ return frozenset({"str"})
406
+ case EnumRef(cls=cls):
407
+ by_value = json_values(cls)
408
+ return frozenset(
409
+ {"str"}
410
+ if by_value is None
411
+ else {"str" if type(v) is str else "int" for v in by_value}
412
+ )
413
+ case Date() | Time() | DateTime() | NaiveDateTime() | Uuid():
414
+ return frozenset({f"str:{type(t).__name__}"})
415
+ case TimeDelta() | Decimal():
416
+ return frozenset({f"str:{type(t).__name__}"})
417
+ case Sequence() | Tuple() | Set() | Array():
418
+ return frozenset({"array"})
419
+ case StructRef() | Shared() | Indirect() | Map():
420
+ return frozenset({"object"})
421
+ case Union(discriminated=True):
422
+ return frozenset({"object"})
423
+ case Optional() | Union():
424
+ raise ValueError(f"{t} is not a union member")
425
+
426
+
427
+ def json_collision(t: Union) -> tuple[Type, Type] | None:
428
+ """Two members of a plain union which cannot be told apart in JSON, if any: a value of one may be taken for one
429
+ of the other, as any string may be for a string of a form"""
430
+ if t.discriminated:
431
+ return None
432
+ kinds = [json_kinds(member) for member in t.members]
433
+ for i, first in enumerate(kinds):
434
+ for j in range(i + 1, len(kinds)):
435
+ strings = [
436
+ {k for k in each if k.startswith("str")} for each in (first, kinds[j])
437
+ ]
438
+ if (
439
+ first & kinds[j]
440
+ or ("str" in strings[0] and strings[1])
441
+ or ("str" in strings[1] and strings[0])
442
+ ):
443
+ return t.members[i], t.members[j]
444
+ return None
445
+
446
+
447
+ def wire_kind(t: Type) -> tuple[str, ...]:
448
+ """How t is represented when serialised: plain union members must differ by this, else need discrimination"""
449
+ match t:
450
+ case Bool():
451
+ return ("bool",)
452
+ case Int() | Date() | Time() | NaiveDateTime() | TimeDelta():
453
+ return ("int",)
454
+ case Float():
455
+ return ("float",)
456
+ case Str() | EnumRef() | Decimal():
457
+ return ("str",)
458
+ case Bytes() | Sequence(Int(bits=8, signed=False)) | Uuid():
459
+ # Bytes natively too: a std::vector of them
460
+ return ("bin",)
461
+ case DateTime():
462
+ return ("timestamp",)
463
+ case StructRef() | Indirect() | Map():
464
+ return ("map",)
465
+ case Sequence() | Tuple() | Set():
466
+ return ("array",)
467
+ case Shared(target):
468
+ # The reference names its target's type
469
+ return ("ref", target.module, target.name)
470
+ case Union(discriminated=True):
471
+ return ("map",)
472
+ case Optional() | Union() | Array():
473
+ raise ValueError(f"{t} is not a union member")
474
+
475
+
476
+ def conforms(t: Type, value: Any, schema: "Schema | None" = None) -> bool:
477
+ """Whether value is valid for t: with schema, also checks the fields of struct values"""
478
+ match t:
479
+ case Bool():
480
+ return type(value) is bool
481
+ case Int():
482
+ return type(value) is int and t.min <= value <= t.max
483
+ case Float():
484
+ return type(value) in (float, int)
485
+ case Str():
486
+ return type(value) is str
487
+ case Bytes():
488
+ return type(value) is bytes
489
+ case Date():
490
+ return type(value) is dt.date
491
+ case Time():
492
+ return type(value) is dt.time and value.tzinfo is None
493
+ case DateTime():
494
+ return type(value) is dt.datetime and value.utcoffset() is not None
495
+ case NaiveDateTime():
496
+ return type(value) is dt.datetime and value.tzinfo is None
497
+ case TimeDelta():
498
+ return type(value) is dt.timedelta
499
+ case Uuid():
500
+ return type(value) is uuid.UUID
501
+ case Decimal():
502
+ if type(value) is not decimal.Decimal:
503
+ return False
504
+ with suppress(ValueError):
505
+ t.unscaled(value)
506
+ return True
507
+ return False
508
+ case EnumRef(cls=cls):
509
+ return type(value) is cls
510
+ case StructRef() | Shared(target=StructRef()) | Indirect(target=StructRef()):
511
+ ref = t if isinstance(t, StructRef) else t.target
512
+ if type(value) is not ref.cls:
513
+ return False
514
+ return schema is None or all(
515
+ conforms(f.type, getattr(value, f.name), schema)
516
+ for f in schema.struct(ref).fields
517
+ )
518
+ case Optional(inner):
519
+ return value is None or conforms(inner, value, schema)
520
+ case Sequence(element):
521
+ return type(value) is tuple and all(
522
+ conforms(element, v, schema) for v in value
523
+ )
524
+ case Array():
525
+ # Which has no default, and is in no union
526
+ return False
527
+ case Tuple(elements):
528
+ return (
529
+ type(value) is tuple
530
+ and len(value) == len(elements)
531
+ and all(
532
+ conforms(e, v, schema) for e, v in zip(elements, value, strict=True)
533
+ )
534
+ )
535
+ case Set(element):
536
+ return type(value) is frozenset and all(
537
+ conforms(element, v, schema) for v in value
538
+ )
539
+ case Map(key, val):
540
+ return isinstance(value, Mapping) and all(
541
+ conforms(key, k, schema) and conforms(val, v, schema)
542
+ for k, v in value.items()
543
+ )
544
+ case Union(members):
545
+ return any(conforms(m, value, schema) for m in members)
546
+
547
+
548
+ def union_member(u: Union, value: Any, schema: "Schema | None" = None) -> int:
549
+ """The index of the first member of u that value conforms to"""
550
+ for i, member in enumerate(u.members):
551
+ if conforms(member, value, schema):
552
+ return i
553
+ raise ValueError(f"{value!r} conforms to no member of {u}")
@@ -0,0 +1,103 @@
1
+ """
2
+ Annotations for schema fields, beyond the builtin types:
3
+
4
+ - Sized numbers, e.g. Int32 or Float32 (int and float are 64-bit)
5
+ - Shared[T]: the field shares its value, rather than holding its own copy, and is serialised by reference
6
+ - DiscriminatedUnion[A, B, ...]: a union serialised with a tag naming the member type
7
+ - NaiveDatetime: a datetime with no timezone
8
+ - DecimalPlaces(2): the number of decimal places of a Decimal
9
+
10
+ None of these depend on the rest of dataclass_native: to type checkers, they are the types they annotate.
11
+ """
12
+
13
+ import datetime as dt
14
+ from dataclasses import dataclass
15
+ from typing import TYPE_CHECKING, Annotated, TypeVar, Union
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class IntSpec:
20
+ bits: int
21
+ signed: bool = True
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class FloatSpec:
26
+ bits: int
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class DecimalPlaces:
31
+ """
32
+ Annotated metadata giving the number of decimal places which a Decimal field holds: Annotated[Decimal,
33
+ DecimalPlaces(2)]. pydantic's Field(decimal_places=2) and condecimal(decimal_places=2) say the same.
34
+ """
35
+
36
+ decimal_places: int
37
+
38
+
39
+ Int8 = Annotated[int, IntSpec(8)]
40
+ Int16 = Annotated[int, IntSpec(16)]
41
+ Int32 = Annotated[int, IntSpec(32)]
42
+ Int64 = Annotated[int, IntSpec(64)]
43
+ UInt8 = Annotated[int, IntSpec(8, signed=False)]
44
+ UInt16 = Annotated[int, IntSpec(16, signed=False)]
45
+ UInt32 = Annotated[int, IntSpec(32, signed=False)]
46
+ UInt64 = Annotated[int, IntSpec(64, signed=False)]
47
+ Float32 = Annotated[float, FloatSpec(32)]
48
+ Float64 = Annotated[float, FloatSpec(64)]
49
+
50
+
51
+ class SharedMarker:
52
+ """Annotated metadata marking a field as Shared"""
53
+
54
+ def __repr__(self) -> str:
55
+ return "Shared"
56
+
57
+
58
+ class DiscriminatedMarker:
59
+ """Annotated metadata marking a union as discriminated"""
60
+
61
+ def __repr__(self) -> str:
62
+ return "Discriminated"
63
+
64
+
65
+ class NaiveMarker:
66
+ """Annotated metadata marking a datetime as having no timezone"""
67
+
68
+ def __repr__(self) -> str:
69
+ return "Naive"
70
+
71
+
72
+ SHARED = SharedMarker()
73
+ DISCRIMINATED = DiscriminatedMarker()
74
+ NAIVE = NaiveMarker()
75
+
76
+ NaiveDatetime = Annotated[dt.datetime, NAIVE]
77
+ """
78
+ A datetime with no timezone: a date and a time of day, wherever it is, not an instant. A plain datetime must have a
79
+ timezone. pydantic's NaiveDatetime means the same.
80
+ """
81
+
82
+ T = TypeVar("T")
83
+
84
+ Shared = Annotated[T, SHARED]
85
+ """
86
+ The value is shared, not copied: Shared[A], Shared[A | B], Shared[A] | None.
87
+
88
+ Natively a reference-counted pointer to an immutable value, compared by value. Serialised once per write, with
89
+ references to it, so that sharing survives a round trip and unions of shared types need no union columns.
90
+ """
91
+
92
+ if TYPE_CHECKING:
93
+ # For type checkers, a union of its members
94
+ DiscriminatedUnion = Union
95
+ else:
96
+
97
+ class DiscriminatedUnion:
98
+ """A union serialised as {"t": tag, "v": value}, the tag naming the member's type"""
99
+
100
+ def __class_getitem__(cls, params):
101
+ if not isinstance(params, tuple) or len(params) < 2:
102
+ raise TypeError("DiscriminatedUnion needs at least two types")
103
+ return Annotated[Union[params], DISCRIMINATED] # noqa: UP007