From fc2a0ff6bb4573d294e09dfc3c04b130bf0dc918 Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Mon, 30 Nov 2026 16:34:51 +0000 Subject: [PATCH] Take DiscriminatedUnion and Shared from pydantic-addons, by which pydantic writes a DiscriminatedUnion as this does --- DESIGN.md | 5 +- JSON_FORMAT.md | 6 ++- README.md | 4 ++ pyproject.toml | 1 + src/dataclass_native/_native.py | 5 ++ src/dataclass_native/types.py | 91 ++++++++++++++++++--------------- tests/test_json.py | 30 ++++++++++- uv.lock | 11 ++++ 8 files changed, 108 insertions(+), 45 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 17f43d5..e742217 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -509,7 +509,10 @@ what an object is made from, before the native class checks it. - When generating from explicit modules, all their dependency modules are generated too. Is a `--no-deps` option needed for dependencies generated by another project? - Should what this has in common with [pypersistable](https://github.com/nickyoung-github/pypersistable) be a - package of its own? Both map Python types to Arrow, and each has its own `DiscriminatedUnion`. + package of its own? Both map Python types to Arrow. `DiscriminatedUnion` and `Shared` now are, in + [pydantic-addons](https://github.com/nickyoung-github/pydantic-addons), which has no dependencies: it tells + pydantic, if that is installed, to write a `DiscriminatedUnion` as this does, by the same tags. A class's tag + from `@native(tag=...)` is given to it too, and the sizes of int and float, and `NaiveDatetime`, say theirs. - Should `arrow.hpp` use nanoarrow after all, at least to read? It would check that the tables given are valid Arrow, which ours trusts, read more layouts natively (large strings), and replace about a fifth of the file: the ownership and buffers, not the mapping of our types. Against that, it is a C source which every extension would diff --git a/JSON_FORMAT.md b/JSON_FORMAT.md index 862a55f..619cdfd 100644 --- a/JSON_FORMAT.md +++ b/JSON_FORMAT.md @@ -116,8 +116,10 @@ Written by this, and read by pydantic's `TypeAdapter` of the same type, or the r - `bytes` need `ser_json_bytes="base64"` and `val_json_bytes="base64"`, as pydantic's default is to write them as text. - A float which is not finite needs `ser_json_inf_nan="strings"`, as pydantic's default is to write `null`. -- pydantic writes a `DiscriminatedUnion` as its member, not as `{"t": ..., "v": ...}`, and a `tuple[UInt8, ...]` as - an array of numbers, so of these neither reads the other's. Nor does pydantic read a numpy array. +- A `DiscriminatedUnion` is [pydantic-addons](https://github.com/nickyoung-github/pydantic-addons)', which + tells pydantic to write and read it as `{"t": ..., "v": ...}`, with these tags. +- pydantic writes a `tuple[UInt8, ...]` as an array of numbers, so of that neither reads the other's. Nor does + pydantic read a numpy array. - pydantic does not read an object whose keys are of an enum of ints, though it writes one as this does. - pydantic reads a datetime with the offset it was written with, and this reads it as UTC: they are equal. diff --git a/README.md b/README.md index 928bb7a..dd7b295 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,10 @@ needs numpy: install `dataclass-native[numpy]`. A class may also be a pydantic dataclass (`pydantic.dataclasses.dataclass(frozen=True)`), to validate and convert what its objects are made from. pydantic's `BaseModel` is not supported, it does unfortunate things like setting `__dict__` directly on objects and has complicated (and rather ugly) code in `__setattr__` etc, which interferes with the descriptors. `BaseModel` and descriptors are generally unhappy bedfellows. +`DiscriminatedUnion` and `Shared` are those of [pydantic-addons](https://github.com/nickyoung-github/pydantic-addons), +which is installed with this and has no dependencies of its own: so pydantic, where it is used, writes and reads a +`DiscriminatedUnion` as this does. + ### Frozen or not A class may be frozen (`@dataclass(frozen=True)`) or not. Frozen is the better default: the differences are diff --git a/pyproject.toml b/pyproject.toml index 3329dcc..4757496 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,7 @@ dynamic = ["version"] dependencies = [ "jinja2>=3.1.6", + "pydantic-addons>=1.0.0", ] [project.scripts] diff --git a/src/dataclass_native/_native.py b/src/dataclass_native/_native.py index be48a9d..05e8e0c 100644 --- a/src/dataclass_native/_native.py +++ b/src/dataclass_native/_native.py @@ -9,6 +9,8 @@ from typing import Any, overload from weakref import WeakKeyDictionary +from pydantic_addons import tagged + from ._mode import Mode, _fix_mode @@ -48,6 +50,9 @@ def native(cls: Any = None, /, *, tag: str | None = None) -> Any: def decorate(cls: type) -> type: _validate(cls) _registry[cls] = NativeInfo(tag=tag or f"{cls.__module__}.{cls.__qualname__}") + if tag: + # So that pydantic writes it by this too, in a DiscriminatedUnion + tagged(tag)(cls) _compare_arrays(cls) if (mode := _fix_mode()) is not Mode.PURE: _install_binding(cls, required=mode is Mode.STRICT) diff --git a/src/dataclass_native/types.py b/src/dataclass_native/types.py index 46bfa98..54f4de6 100644 --- a/src/dataclass_native/types.py +++ b/src/dataclass_native/types.py @@ -4,6 +4,7 @@ - Sized numbers, e.g. Int32 or Float32 (int and float are 64-bit) - Shared[T]: the field shares its value, rather than holding its own copy, and is serialised by reference - DiscriminatedUnion[A, B, ...]: a union serialised with a tag naming the member type + Both are pydantic-addons', which pydantic reads and writes too - NaiveDatetime: a datetime with no timezone - DecimalPlaces(2): the number of decimal places of a Decimal @@ -12,7 +13,41 @@ import datetime as dt from dataclasses import dataclass -from typing import TYPE_CHECKING, Annotated, TypeVar, Union +from typing import Annotated + +from pydantic_addons import ( + DISCRIMINATED, + SHARED, + DiscriminatedMarker, + DiscriminatedUnion, + Shared, + SharedMarker, +) + +__all__ = [ + "DISCRIMINATED", + "NAIVE", + "SHARED", + "DecimalPlaces", + "DiscriminatedMarker", + "DiscriminatedUnion", + "Float32", + "Float64", + "FloatSpec", + "Int8", + "Int16", + "Int32", + "Int64", + "IntSpec", + "NaiveDatetime", + "NaiveMarker", + "Shared", + "SharedMarker", + "UInt8", + "UInt16", + "UInt32", + "UInt64", +] @dataclass(frozen=True) @@ -20,11 +55,24 @@ class IntSpec: bits: int signed: bool = True + @property + def __tag__(self) -> str: + """Which names the type in a DiscriminatedUnion: as pydantic-addons asks""" + return ( + "int" + if self == IntSpec(64) + else f"{'' if self.signed else 'u'}int{self.bits}" + ) + @dataclass(frozen=True) class FloatSpec: bits: int + @property + def __tag__(self) -> str: + return "float" if self.bits == 64 else f"float{self.bits}" + @dataclass(frozen=True) class DecimalPlaces: @@ -48,29 +96,15 @@ class DecimalPlaces: Float64 = Annotated[float, FloatSpec(64)] -class SharedMarker: - """Annotated metadata marking a field as Shared""" - - def __repr__(self) -> str: - return "Shared" - - -class DiscriminatedMarker: - """Annotated metadata marking a union as discriminated""" - - def __repr__(self) -> str: - return "Discriminated" - - class NaiveMarker: """Annotated metadata marking a datetime as having no timezone""" + __tag__ = "naivedatetime" + def __repr__(self) -> str: return "Naive" -SHARED = SharedMarker() -DISCRIMINATED = DiscriminatedMarker() NAIVE = NaiveMarker() NaiveDatetime = Annotated[dt.datetime, NAIVE] @@ -78,26 +112,3 @@ def __repr__(self) -> str: A datetime with no timezone: a date and a time of day, wherever it is, not an instant. A plain datetime must have a timezone. pydantic's NaiveDatetime means the same. """ - -T = TypeVar("T") - -Shared = Annotated[T, SHARED] -""" -The value is shared, not copied: Shared[A], Shared[A | B], Shared[A] | None. - -Natively a reference-counted pointer to an immutable value, compared by value. Serialised once per write, with -references to it, so that sharing survives a round trip and unions of shared types need no union columns. -""" - -if TYPE_CHECKING: - # For type checkers, a union of its members - DiscriminatedUnion = Union -else: - - class DiscriminatedUnion: - """A union serialised as {"t": tag, "v": value}, the tag naming the member's type""" - - def __class_getitem__(cls, params): - if not isinstance(params, tuple) or len(params) < 2: - raise TypeError("DiscriminatedUnion needs at least two types") - return Annotated[Union[params], DISCRIMINATED] # noqa: UP007 diff --git a/tests/test_json.py b/tests/test_json.py index c204d1a..266d8b6 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -582,8 +582,8 @@ def test_objects_which_are_not_frozen(): ) -# Which pydantic writes as its member, and as an array of numbers -NOT_AS_PYDANTIC = (DiscriminatedUnion[str, bytes], tuple[UInt8, ...], Money) +# Which pydantic writes as an array of numbers, and by the number of its currency's name +NOT_AS_PYDANTIC = (tuple[UInt8, ...], Money) # Nor what it wrote itself: a key which is of an enum of ints PYDANTIC_DOES_NOT_READ = (Mapping[Currency, Side],) @@ -599,6 +599,25 @@ def test_pydantic_reads_and_writes_values(tp, value): assert from_json(tp, adapter.dump_json(value)) == value +def test_tags_are_those_pydantic_addons_gives(): + """By which pydantic writes a DiscriminatedUnion as this does: of a size of number, and of a class given one""" + from pydantic_addons import tag + + from dataclass_native import Float64, Int64, UInt64 + from dataclass_native.introspect import _tag, resolve + + scalars = (bool, int, Int8, Int64, UInt8, UInt64, float, Float32, Float64, str) + others = (bytes, dt.date, dt.time, dt.datetime, NaiveDatetime, dt.timedelta, UUID) + for tp in (*scalars, *others, Price, Side, Currency, Money, Party, Shared[Party]): + assert tag(tp) == _tag(resolve(tp, "here")), tp + assert tag(Party) == "party.v1" and tag(UInt8) == "uint8" + adapter = TypeAdapter(DiscriminatedUnion[Int8, Float32, str]) + for value, text in ((5, '{"t":"int8","v":5}'), (0.5, '{"t":"float32","v":0.5}')): + assert to_json(value, DiscriminatedUnion[Int8, Float32, str]) == text.encode() + assert adapter.dump_json(value) == text.encode() + assert adapter.validate_json(text) == value + + def test_pydantic_reads_and_writes_classes(): party = Party("Acme", "LEI1", 3) values = ( @@ -616,6 +635,13 @@ def test_pydantic_reads_and_writes_classes(): Holder("ann", party), Money(1.0, Currency.USD), 5, 0.25, ("a",), Side.SELL ), Address("London", ("1 High St",)), + # With a DiscriminatedUnion, which pydantic-addons tells pydantic to write as this does: of a class, of + # an int, and of classes which are Shared, one of them of a tag of its own + _order(), + Order(Customer("ann", Address("London")), 1.0, (), 7), + Dealt(party, (Fund("F", "L2", 1, "Ann"), party)), + Scheduled(dt.datetime(2026, 5, 6), tagged=dt.datetime(2026, 1, 1)), + Priced(Decimal("1.50"), Decimal("0.000001"), tagged=Decimal("8.25")), ) for value in values: adapter = TypeAdapter(type(value)) diff --git a/uv.lock b/uv.lock index 8292d3a..3cdfe93 100644 --- a/uv.lock +++ b/uv.lock @@ -156,6 +156,7 @@ name = "dataclass-native" source = { editable = "." } dependencies = [ { name = "jinja2" }, + { name = "pydantic-addons" }, ] [package.optional-dependencies] @@ -192,6 +193,7 @@ requires-dist = [ { name = "numpy", marker = "extra == 'numpy'", specifier = ">=2.5.5" }, { name = "pyarrow", marker = "extra == 'arrow'", specifier = ">=26.0.1" }, { name = "pydantic", marker = "extra == 'pydantic'", specifier = ">=2.8" }, + { name = "pydantic-addons", specifier = ">=1.0.0" }, { name = "tzdata", marker = "sys_platform == 'win32' and extra == 'arrow'", specifier = ">=2026.6" }, ] provides-extras = ["numpy", "pydantic", "arrow"] @@ -605,6 +607,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/8c/824a686c4ba815ddb0722f9e66272088bccd4e1ae1d2f7015375e4a4fc7f/pydantic-2.14.4-py3-none-any.whl", hash = "sha256:653a2ad9f6d8858529c77c72717d0ea991d6c6837fe683246b2f4b2bbfc3fadc", size = 494865, upload-time = "2026-11-19T12:57:37.688Z" }, ] +[[package]] +name = "pydantic-addons" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2e/d8/eac787f05aa13a9768b146a60fd0dda9e756e3a8387fcf11045a11e420c0/pydantic_addons-1.0.0.tar.gz", hash = "sha256:24f79d7260e3539afb90427ef8e340d57f654416e725ef95d5ccff1849709f50", size = 44092, upload-time = "2026-11-30T16:31:20.227Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/67/3b161b67fcc5311caeea176f6473cbaed6d248393652d5aae710cb750fc1/pydantic_addons-1.0.0-py3-none-any.whl", hash = "sha256:92d4af45053ca23014ad2200d2fa31bdccf4b7770aa485302ff0db5050585e5b", size = 8758, upload-time = "2026-11-30T16:31:19.211Z" }, +] + [[package]] name = "pydantic-core" version = "2.50.5"