Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions JSON_FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dynamic = ["version"]

dependencies = [
"jinja2>=3.1.6",
"pydantic-addons>=1.0.0",
]

[project.scripts]
Expand Down
5 changes: 5 additions & 0 deletions src/dataclass_native/_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
from typing import Any, overload
from weakref import WeakKeyDictionary

from pydantic_addons import tagged

from ._mode import Mode, _fix_mode


Expand Down Expand Up @@ -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)
Expand Down
91 changes: 51 additions & 40 deletions src/dataclass_native/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -12,19 +13,66 @@

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)
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:
Expand All @@ -48,56 +96,19 @@ 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]
"""
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
30 changes: 28 additions & 2 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],)

Expand All @@ -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 = (
Expand All @@ -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))
Expand Down
11 changes: 11 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading