From 04e03ba1f30a21fa4dba0f5caa7fd338950f6569 Mon Sep 17 00:00:00 2001 From: nickyoung-github Date: Mon, 30 Nov 2026 12:37:24 +0000 Subject: [PATCH] Write and read the JSON of what is held in Python by pydantic, where it is installed --- DESIGN.md | 20 + JSON_FORMAT.md | 14 + README.md | 23 +- pyproject.toml | 4 + src/dataclass_native/_json.py | 32 +- src/dataclass_native/_pydantic.py | 594 ++++++++++++++++++++++++++++++ tests/performance.py | 40 +- tests/test_json.py | 176 ++++++++- tests/test_json_in_python.py | 14 + uv.lock | 6 +- 10 files changed, 883 insertions(+), 40 deletions(-) create mode 100644 src/dataclass_native/_pydantic.py create mode 100644 tests/test_json_in_python.py diff --git a/DESIGN.md b/DESIGN.md index c3f1f47..17f43d5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -472,6 +472,26 @@ what an object is made from, before the native class checks it. written to. To come: lists. 7. JSON. The aim is that pydantic's `TypeAdapter` reads what this writes, and this reads what it writes: not that the two write the same. **Done**, in Python and in C++, as [JSON_FORMAT.md](JSON_FORMAT.md) has it. + + **Done:** what Python holds itself, as it does every object in `pure` mode, is written and read by + pydantic-core where pydantic is installed, which is not a dependency: some three times faster for a class, + and up to ten for a value. It is given a schema made from the description of the type, one to write by and + one to read by, so the format is this one's, not that of a `TypeAdapter`: + - pydantic does not validate what it writes: it would write `None` as `null` in any field, and a value of + another type as whatever that is, with at most a warning. So each value is first checked to be of its + type, by a function which pydantic calls: of a tuple, for all of its elements at once where their types + alone say. A union of pydantic's writes what none of its members does as whatever it is, so a + discriminated union is not written as one, and a plain union has a last member which takes such a value + and has what was written discarded. + - What pydantic has no equal of, or writes otherwise, is written and read by the Python codec's own + functions, within what pydantic does: a `Decimal`, `bytes`, a `Float32`, an array, a key which is not a + string, a timedelta which is read, and a plain union of a float and what is written as an integer. + - If pydantic refuses a value or data, the Python codec is then given it: which says why, as before, or + writes or reads what pydantic could not. So the Python codec is still the reference, and what is + refused is the same, but for what [JSON_FORMAT.md](JSON_FORMAT.md) says pydantic reads otherwise. + - A class is made by pydantic as dataclasses make it, with its defaults and its `__post_init__`. One which + is bound to a native class, or which validates, or has a field it is not made from, is left to the + Python codec, as is a type which holds one. 8. More types, each in every layer: the schema, C++, msgpack and Arrow. To revisit: - **Done:** `Decimal`, as Arrow's `decimal128`, its scale declared on the field. To come, if wanted: more than 18 digits, and the digits pydantic's `max_digits` gives as the precision of the Arrow column. diff --git a/JSON_FORMAT.md b/JSON_FORMAT.md index d0fd83f..862a55f 100644 --- a/JSON_FORMAT.md +++ b/JSON_FORMAT.md @@ -6,6 +6,11 @@ Rust implement it, Rust by [serde](https://serde.rs). What is asked of them is l others write: they do also write the same text as each other, but need not. The Python one is the reference: where this document and it disagree, one of them has a bug. +Where pydantic is installed, it is also what writes and reads the objects which Python holds itself, as it does +every object in `pure` mode: several times faster than the Python does, and as this document has it, but for +what is said of it below. It is given a schema made from the type, not the one a `TypeAdapter` would make. The +Python still says why a value or data is refused, and writes and reads what pydantic has no equal of. + A reader is given the type it is to read, as with [msgpack](WIRE_FORMAT.md). ## Values @@ -41,6 +46,9 @@ It is written as UTF-8, with no spaces between its tokens: `to_json` gives `byte writes one: in the fewest digits which read back as it, in full from `0.0001` to `1000000000000000.0` and with an exponent beyond, as `1e-05` and `1e+16`. A `Float32` is written as the `float` of the same value. +pydantic writes a float as it does, which is `0.00001` where Python writes `1e-05`, and a timedelta of a year or +more with its years, as `"P1Y35D"`: each of which the others read. + For example, `Money(1.5, Currency.EUR)`, whose currencies are numbered, is `{"amount":1.5,"currency":2}`. ## Unions @@ -98,6 +106,9 @@ others. Rust reads as serde does, which is otherwise of what none of them writes: `-0` is not an integer to it, and is the float `-0.0`; and the text of a number which is a key may have no spaces about it, as Python allows. +pydantic likewise reads as it does: of a key which is twice in an object, the last; and it does not notice `NaN` +or `Infinity` within an entry which is ignored. + ## With pydantic Written by this, and read by pydantic's `TypeAdapter` of the same type, or the reverse: @@ -110,6 +121,9 @@ Written by this, and read by pydantic's `TypeAdapter` of the same type, or the r - 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. +This is of a `TypeAdapter` of your own. None of it is so of what this writes and reads by pydantic itself, which +is this format. + ## Not decided - Whether a `Shared` object may instead be written once, with what shares it referring to it, as in msgpack: which diff --git a/README.md b/README.md index 6988bd7..928bb7a 100644 --- a/README.md +++ b/README.md @@ -375,7 +375,9 @@ from_json(Trade, data) == trade # True In the format of [JSON_FORMAT.md](JSON_FORMAT.md), which pydantic's `TypeAdapter` of the same class reads, and writes what this reads. An object held by `Shared` fields is written wherever it is held, so is no longer shared when read back. As with msgpack, objects stored natively are written and read by C++, and plain ones by Python, -character for character the same. In C++ of your own: +character for character the same. With pydantic installed (`pip install dataclass-native[pydantic]`), plain ones +are instead written and read by it: in the same format, and several times faster, as +[Performance](#performance) has it. In C++ of your own: ```cpp #include "dataclass_native/json.hpp" @@ -464,17 +466,18 @@ so a class with many defaults, as `Trade` has, costs less to make than its field What is gained is in what native code then does with the structs, without Python: as in serialising. An `Order` here is of two customers, each with two addresses: 15 values, in 7 objects. Arrow is of 10,000 of them. -| Microseconds, for each `Order`, to | `pure` | C++ | Rust | -|---|---:|---:|---:| -| Write msgpack | 8.8 | 1.9 | 1.8 | -| Read msgpack | 24.6 | 2.6 | 2.7 | -| Write JSON | 10.9 | 2.3 | 2.0 | -| Read JSON | 13.6 | 3.2 | 2.7 | -| Write Arrow | 11.3 | 0.4 | 0.3 | -| Read Arrow | 9.4 | 0.7 | 0.8 | +| Microseconds, for each `Order`, to | `pure` | `pure`, with pydantic | C++ | Rust | +|---|---:|---:|---:|---:| +| Write msgpack | 8.8 | | 1.9 | 1.8 | +| Read msgpack | 24.6 | | 2.6 | 2.7 | +| Write JSON | 10.9 | 3.5 | 2.3 | 2.0 | +| Read JSON | 13.6 | 3.6 | 3.2 | 2.7 | +| Write Arrow | 11.3 | | 0.4 | 0.3 | +| Read Arrow | 9.4 | | 0.7 | 0.8 | C++ and Rust write and read the structs themselves: Rust's Arrow with the feature `arrow` of its crate, without -which Python does it, reading each field from the struct, which is slower than `pure`. +which Python does it, reading each field from the struct, which is slower than `pure`. With pydantic installed, +it writes and reads the JSON of plain dataclasses, in place of Python: which has no part in msgpack or Arrow. ## Examples diff --git a/pyproject.toml b/pyproject.toml index e58183f..3329dcc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,6 +32,10 @@ dataclass-native = "dataclass_native.cli:main" numpy = [ "numpy>=2.5.5", ] +# By which the JSON of what is held in Python, as all is in pure mode, is written and read several times faster +pydantic = [ + "pydantic>=2.8", +] # tzdata as, on Windows, pyarrow needs it to give a datetime its timezone, UTC arrow = [ "pyarrow>=26.0.1", diff --git a/src/dataclass_native/_json.py b/src/dataclass_native/_json.py index c7282c7..8dd4a05 100644 --- a/src/dataclass_native/_json.py +++ b/src/dataclass_native/_json.py @@ -1,6 +1,7 @@ """ JSON of @native objects, in the format of JSON_FORMAT.md: such that pydantic reads what this writes, and this reads -what pydantic writes. In Python alone, in every mode. +what pydantic writes. In Python alone, in every mode: but that pydantic, where it is installed, writes and reads +what is held in Python, as _pydantic says. """ import base64 @@ -92,6 +93,12 @@ def to_json(value: Any, tp: Any = None) -> bytes: from ._runtime import native_object return native_object(value).__json__() + if by_pydantic := _by_pydantic(cls if tp is None else tp): + try: + return by_pydantic[0](value) + except Exception: # noqa: BLE001, S110 + # The Python says why, or writes what pydantic does not + pass return write(value, tp) @@ -116,9 +123,32 @@ def from_json(tp: Any, data: str | bytes) -> Any: data.encode() if isinstance(data, str) else bytes(data) ), ) + if by_pydantic := _by_pydantic(tp): + try: + return by_pydantic[1](data) + except Exception: # noqa: BLE001, S110 + # The Python says why, or reads what pydantic does not + pass return read(tp, data) +def _by_pydantic(tp: Any, /) -> Any: + """What writes and reads a type by pydantic, if it is installed and may: see _pydantic""" + global _by_pydantic + # Found when first asked, as pydantic is then imported + _by_pydantic = _pydantic_codec() + return _by_pydantic(tp) + + +def _pydantic_codec() -> Callable[[Any], Any]: + try: + from ._pydantic import codec + except ImportError: + # It is not installed + return lambda tp: None + return codec + + def write(value: Any, tp: Any = None) -> bytes: """As to_json, in Python alone""" plain, _ = _root(type(value) if tp is None else tp) diff --git a/src/dataclass_native/_pydantic.py b/src/dataclass_native/_pydantic.py new file mode 100644 index 0000000..9d42967 --- /dev/null +++ b/src/dataclass_native/_pydantic.py @@ -0,0 +1,594 @@ +""" +JSON by pydantic, if it is installed: of what is held in Python, so of every class in pure mode. pydantic-core writes +and reads a class, a tuple and the commonest values natively, several times faster than the Python of _json does. That +is still what says why a value or data is refused, and what writes and reads the rest, within what pydantic does. + +What it writes and reads is JSON_FORMAT.md's, which the Python reads and writes: but for what that document says +of it. +""" + +import datetime as dt +import math +import re +import uuid +from collections.abc import Callable, Mapping +from dataclasses import MISSING, fields +from operator import itemgetter +from typing import Any + +from pydantic_core import SchemaSerializer, SchemaValidator +from pydantic_core import core_schema as cs + +from . import schema as s +from ._json import _FORMS, _NOT_FINITE, _is_bytes, _object, _plain, _text, _told_apart +from ._wire import ( + _Invalid, + _member, + _name, + _native_class, + _order, + _ordered, + _struct_class, +) +from .introspect import _tag, describe, resolve +from .schema import SchemaError + +# Writes a value of a type as JSON, and reads one from it +type Codec = tuple[Callable[[Any], bytes], Callable[[str | bytes], Any]] + +# The schema of each class, by its reference, which what holds it has: as a class may hold itself +type _Classes = dict[str, cs.CoreSchema | None] + +_STR = frozenset({str}) +_CONFIG = cs.CoreConfig(ser_json_inf_nan="strings") +_codecs: dict[Any, Codec | None] = {} + + +class _NotPlain(Exception): + """A class is not held in Python as dataclasses made it, so pydantic may not make it""" + + +def codec(tp: Any) -> Codec | None: + """What writes and reads a type by pydantic, if it may: else the Python does""" + try: + return _codecs[tp] + except KeyError: + made = _codecs[tp] = _codec(tp) + return made + except TypeError: + # It has no hash + return None + + +def _codec(tp: Any) -> Codec | None: + name = _name(tp) + writes: _Classes = {} + reads: _Classes = {} + try: + t = resolve(tp, name) + written, read = _writes(t, name, writes), _reads(t, name, reads) + except (_NotPlain, SchemaError): + # Which the Python says, of a schema that cannot be written + return None + to_json = SchemaSerializer(_with(written, writes), _CONFIG).to_json + + def write(value: Any) -> bytes: + of_no_member: list[Any] = [] + # By alias, as a discriminated union is written + data = to_json(value, by_alias=True, context=of_no_member) + if of_no_member: + raise _Invalid + return data + + return write, SchemaValidator(_with(read, reads)).validate_json + + +def _with(root: cs.CoreSchema, classes: _Classes) -> cs.CoreSchema: + return cs.definitions_schema(root, [c for c in classes.values() if c]) + + +def _fields(cls: type) -> tuple[s.Field, ...]: + """The fields of a class which pydantic may make: one held in Python, which is made by setting each of them""" + if ( + _native_class(cls) is not None + # Which validates what it is made from + or hasattr(cls, "__pydantic_validator__") + or not all(f.init for f in fields(cls)) + or not cls.__dataclass_params__.init # pyright: ignore[reportAttributeAccessIssue] + # Or it has what is given only to make it + or len(cls.__dataclass_fields__) != len(fields(cls)) # pyright: ignore[reportAttributeAccessIssue] + ): + raise _NotPlain + struct = describe(cls) + assert isinstance(struct, s.Struct) + return struct.fields + + +def _reference(cls: type) -> str: + return f"{cls.__module__}.{cls.__qualname__}:{id(cls)}" + + +def _checked(check: Callable[[Any], Any], schema: cs.CoreSchema) -> cs.CoreSchema: + """Writes what check gives of a value, as the schema does: check raises if the value is not of the type. Not + pydantic's own exception for that, at which it writes the value as whatever it is, and warns""" + return cs.any_schema( + serialization=cs.plain_serializer_function_ser_schema( + check, return_schema=schema + ) + ) + + +def _of_types(t: s.Type) -> tuple[cs.CoreSchema, frozenset[type]] | None: + """Of a type whose values are those of some types of Python's, and are written by pydantic as they are in + Python: the schema by which it writes one, and those types""" + match t: + case s.Bool(): + return cs.bool_schema(), frozenset({bool}) + case s.Float(bits=64): + # An int is written as the float it is + return cs.float_schema(), frozenset({float, int}) + case s.Str(): + return cs.str_schema(), frozenset({str}) + case s.Date(): + return cs.date_schema(), frozenset({dt.date}) + case s.TimeDelta(): + # Of a year or more, with its years, each of 365 days + return cs.timedelta_schema(), frozenset({dt.timedelta}) + case s.Uuid(): + return cs.uuid_schema(), frozenset({uuid.UUID}) + case s.EnumRef(cls=enum) if s.json_values(enum) is not None: + return cs.enum_schema(enum, list(enum)), frozenset({enum}) + case _: + return None + + +def _each( + t: s.Type, where: str, classes: _Classes +) -> tuple[cs.CoreSchema, frozenset[type] | None]: + """The schema by which pydantic writes each of many values of the type: and the types they are all to be of, + where their types say that they are of it, which are then asked at once rather than of each as it is written""" + return _of_types(t) or (_writes(t, where, classes), None) + + +def _writes(t: s.Type, where: str, classes: _Classes) -> cs.CoreSchema: + """The schema by which pydantic writes a value of the type, having checked that it is one: as pydantic, which + does not validate what it writes, would write one of another type as whatever that is""" + if cls := _struct_class(t): + reference = _reference(cls) + if reference not in classes: + classes[reference] = None + written = cs.dataclass_schema( + cls, + cs.dataclass_args_schema( + cls.__name__, + [ + cs.dataclass_field( + f.name, + _writes(f.type, f"{cls.__qualname__}.{f.name}", classes), + ) + for f in _fields(cls) + ], + ), + [f.name for f in _fields(cls)], + # Its own, not that of what holds it + config=_CONFIG, + ) + + def exactly(value: Any) -> Any: + # As a subclass is another struct + if type(value) is not cls: + raise _Invalid + return value + + classes[reference] = cs.any_schema( + ref=reference, + serialization=cs.plain_serializer_function_ser_schema( + exactly, return_schema=written + ), + ) + return cs.definition_reference_schema(reference) + + match t: + case s.Float(bits=64): + + def real(value: Any) -> float: + if type(value) is float: + return value + if type(value) is int: + # As a float, which is all pydantic writes as one where it is to be of the type exactly + return float(value) + raise _Invalid + + return _checked(real, cs.float_schema()) + + case s.Int(min=low, max=high): + + def whole(value: Any) -> int: + if type(value) is not int or not low <= value <= high: + raise _Invalid + return value + + return _checked(whole, cs.int_schema()) + + case s.Time(): + + def of_day(value: Any) -> dt.time: + if type(value) is not dt.time or value.tzinfo is not None: + raise _Invalid + return value + + return _checked(of_day, cs.time_schema()) + + case s.DateTime(): + + def instant(value: Any) -> dt.datetime: + if type(value) is not dt.datetime or value.utcoffset() is None: + raise _Invalid + # In UTC, which it is read back as + return value if value.tzinfo is dt.UTC else value.astimezone(dt.UTC) + + return _checked(instant, cs.datetime_schema()) + + case s.NaiveDateTime(): + + def local(value: Any) -> dt.datetime: + if type(value) is not dt.datetime or value.tzinfo is not None: + raise _Invalid + return value + + return _checked(local, cs.datetime_schema()) + + case s.Optional(inner): + return cs.nullable_schema(_writes(inner, where, classes)) + + case s.Sequence(element) if not _is_bytes(t): + schema, types = _each(element, where, classes) + + def of_all(value: Any) -> Any: + if type(value) is not tuple or ( + types and not types.issuperset(map(type, value)) + ): + raise _Invalid + return value + + return _checked(of_all, cs.tuple_schema([schema], variadic_item_index=0)) + + case s.Tuple(elements): + size = len(elements) + + def sized(value: Any) -> Any: + if type(value) is not tuple or len(value) != size: + raise _Invalid + return value + + return _checked( + sized, cs.tuple_schema([_writes(e, where, classes) for e in elements]) + ) + + case s.Set(element): + schema, types = _each(element, where, classes) + order = _order(element) + + def ascending(value: Any) -> list[Any]: + if type(value) is not frozenset or ( + types and not types.issuperset(map(type, value)) + ): + raise _Invalid + return _ordered(value, order) + + return _checked(ascending, cs.list_schema(schema)) + + case s.Map(key_type, value_type): + schema, types = _each(value_type, where, classes) + name, _ = _text(key_type) + order, text = _order(key_type), isinstance(key_type, s.Str) + + def named(value: Any) -> dict[str, Any]: + if not (type(value) is dict or isinstance(value, Mapping)) or ( + types and not types.issuperset(map(type, value.values())) + ): + raise _Invalid + if text and _STR.issuperset(map(type, value)): + # Each is its own name, if it is text: half of a character is not, which pydantic would write + "".join(value).encode() + # No two are the same, so no values are compared + return dict(sorted(value.items())) + return {name(k): value[k] for k in _ordered(value, order)} + + return _checked(named, cs.dict_schema(cs.str_schema(), schema)) + + case s.Union(members, discriminated=True): + # With a field for each member, each written as "v": one of which a value is given as, so that pydantic + # writes it as that member. Not as a union of its own, which writes what no member does as whatever + # it is + keyed = [(_tag(member), str(index)) for index, member in enumerate(members)] + by_type = _by_type(members, keyed) + + def tagged(value: Any) -> dict[str, Any]: + tag, key = by_type.get(type(value)) or keyed[_member(members, value)] + return {"t": tag, key: value} + + return _checked( + tagged, + cs.typed_dict_schema( + {"t": cs.typed_dict_field(cs.str_schema())} + | { + key: cs.typed_dict_field( + _writes(member, where, classes), + required=False, + serialization_alias="v", + ) + for member, (_, key) in zip(members, keyed, strict=True) + } + ), + ) + + case s.Union(members) if s.Float(32) not in members: + _told_apart(t, where) + # pydantic writes a value as the first member which does not refuse it: so as that it is of, by its type + choices: list[Any] = [ + _writes(member, where, classes) + for member in members + if member != s.Float() + ] + if s.Float() in members: + # One which is not finite would be read as the string it is written as, where a string is a member + finite = any("str" in s.json_kinds(member) for member in members) + + def real_alone(value: Any) -> float: + if type(value) is not float or finite and not math.isfinite(value): + raise _Invalid + return value + + def whole_real(value: Any) -> float: + if type(value) is not int: + raise _Invalid + return float(value) + + # An int is a float only if not of another member + choices = [ + _checked(real_alone, cs.float_schema()), + *choices, + _checked(whole_real, cs.float_schema()), + ] + return cs.union_schema([*choices, _OF_NO_MEMBER]) + + case _: + if of_types := _of_types(t): + schema, types = of_types + + def of_type(value: Any) -> Any: + if type(value) not in types: + raise _Invalid + return value + + return _checked(of_type, schema) + + # What pydantic has no equal of, or writes otherwise: as the Python writes it + plain = _plain(t, where) + return cs.any_schema( + serialization=cs.plain_serializer_function_ser_schema( + lambda value: plain(value, 0) + ) + ) + + +def _of_no_member(value: Any, info: Any): + # Which pydantic would else write as whatever it is: so it is told of, and what is written is not kept + info.context.append(value) + + +_OF_NO_MEMBER = cs.any_schema( + serialization=cs.plain_serializer_function_ser_schema(_of_no_member, info_arg=True) +) + + +def _by_type(members: tuple[s.Type, ...], tags: list[Any]) -> dict[type, Any]: + """The tag of the member of a union which a value is of, by the type of the value: for those types which alone + say, as most do, so that each member need not be asked in turn""" + plain = {s.Bool: bool, s.Float: float, s.Str: str, s.Bytes: bytes} + by_type: dict[type, Any] = {} + for member, tag in zip(members, tags, strict=True): + held = ( + member.cls + if isinstance(member, s.EnumRef) + else _struct_class(member) or plain.get(type(member)) + ) + if held: + by_type.setdefault(held, tag) + whole = [isinstance(member, s.Int) for member in members] + if sum(whole) == 1 and s.Float not in map(type, members): + # Else which it is of is by its size, or it may be a float + by_type[int] = tags[whole.index(True)] + return by_type + + +def _tagged(member: cs.CoreSchema) -> cs.CoreSchema: + """A member of a discriminated union, with its tag""" + return cs.typed_dict_schema( + { + "t": cs.typed_dict_field(cs.str_schema(strict=True)), + "v": cs.typed_dict_field(member), + }, + extra_behavior="forbid", + ) + + +def _formed(t: s.Type, schema: cs.CoreSchema) -> cs.CoreSchema: + """Reads a string of the form of the type, and no other which pydantic would read as one, by the schema""" + form = _FORMS[type(t)] + # Of the ASCII digits, as the form is: and all of the string + pattern = f"^(?{'i' if form.flags & re.IGNORECASE else ''}:{form.pattern})$" + return cs.chain_schema( + [cs.str_schema(strict=True, pattern=pattern.replace(r"\d", "[0-9]")), schema] + ) + + +def _utc(value: dt.datetime) -> dt.datetime: + """A datetime which pydantic read, in UTC: which it is of whatever offset it was written with""" + if value.utcoffset(): + return value.astimezone(dt.UTC) + return value.replace(tzinfo=dt.UTC) + + +def _reads(t: s.Type, where: str, classes: _Classes) -> cs.CoreSchema: + """The schema by which pydantic reads a value of the type: of what the Python reads as one, and no more""" + if cls := _struct_class(t): + reference = _reference(cls) + if reference not in classes: + classes[reference] = None + read = [] + for described, f in zip(_fields(cls), fields(cls), strict=True): + field = _reads(described.type, f"{cls.__qualname__}.{f.name}", classes) + # One which is not written takes its default, and what is not a field is ignored + if f.default is not MISSING: + field = cs.with_default_schema(field, default=f.default) + elif f.default_factory is not MISSING: + field = cs.with_default_schema( + field, default_factory=f.default_factory + ) + read.append(cs.dataclass_field(f.name, field)) + classes[reference] = cs.dataclass_schema( + cls, + cs.dataclass_args_schema(cls.__name__, read, extra_behavior="ignore"), + [f.name for f in fields(cls)], + ref=reference, + post_init=hasattr(cls, "__post_init__"), + ) + return cs.definition_reference_schema(reference) + + match t: + case s.Bool(): + return cs.bool_schema(strict=True) + + case s.Int(min=low, max=high): + return cs.int_schema(ge=low, le=high, strict=True) + + case s.Float(bits=64): + # Of either kind of number, or the string of one which is not finite + return cs.union_schema([_FINITE, _NOT_FINITE_READ]) + + case s.Str(): + return cs.str_schema(strict=True) + + case s.Date(): + return _formed(t, cs.date_schema()) + + case s.Time(): + return _formed(t, cs.time_schema()) + + case s.DateTime(): + return cs.no_info_after_validator_function( + _utc, _formed(t, cs.datetime_schema()) + ) + + case s.NaiveDateTime(): + return _formed(t, cs.datetime_schema()) + + case s.Uuid(): + return _formed(t, cs.uuid_schema()) + + case s.EnumRef(cls=enum) if s.json_values(enum) is not None: + # A member's value, which is not then a number with a fraction, nor a bool + return cs.chain_schema( + [ + cs.union_schema( + [cs.int_schema(strict=True), cs.str_schema(strict=True)] + ), + cs.enum_schema(enum, list(enum)), + ] + ) + + case s.Optional(inner): + return cs.nullable_schema(_reads(inner, where, classes)) + + case s.Sequence(element) if not _is_bytes(t): + return cs.tuple_schema( + [_reads(element, where, classes)], variadic_item_index=0, strict=True + ) + + case s.Tuple(elements): + return cs.tuple_schema( + [_reads(e, where, classes) for e in elements], strict=True + ) + + case s.Set(element): + + def distinct(read: list[Any]) -> frozenset[Any]: + made = frozenset(read) + if len(made) != len(read): + raise ValueError("an element twice") + return made + + return cs.no_info_after_validator_function( + distinct, cs.list_schema(_reads(element, where, classes), strict=True) + ) + + case s.Map(key_type, value_type): + entries = cs.dict_schema( + cs.str_schema(strict=True), + _reads(value_type, where, classes), + strict=True, + ) + if isinstance(key_type, s.Str): + return entries + _, key = _text(key_type) + + def keyed(read: dict[str, Any]) -> dict[Any, Any]: + try: + made = {key(k): v for k, v in read.items()} + except _Invalid: + raise ValueError("a key") from None + if len(made) != len(read): + raise ValueError("a key twice, though written differently") + return made + + return cs.no_info_after_validator_function(keyed, entries) + + case s.Union(members, discriminated=True): + return cs.no_info_after_validator_function( + itemgetter("v"), + cs.tagged_union_schema( + { + _tag(member): _tagged(_reads(member, where, classes)) + for member in members + }, + "t", + strict=True, + ), + ) + + case s.Union(members) if s.Float(32) not in members and ( + s.Float(64) not in members + or not any("int" in s.json_kinds(member) for member in members) + ): + # Each kind of JSON value is of one member, but a string, which is of whichever first reads it. With + # both a float and what is written as an integer, pydantic would read as the float an integer which + # the other does not: so the Python reads that + _told_apart(t, where) + choices: list[Any] = [_reads(member, where, classes) for member in members] + if any("str" in s.json_kinds(member) for member in members): + # The string of a float which is not finite is then a string + choices = [ + _FINITE if member == s.Float(64) else schema + for member, schema in zip(members, choices, strict=True) + ] + return cs.union_schema(choices, mode="left_to_right") + + case _: + # As the Python reads it, of what pydantic read as JSON + make = _object(t, where) + + def by_python(read: Any) -> Any: + try: + return make(read) + except _Invalid: + raise ValueError("as the Python reads it") from None + + return cs.no_info_plain_validator_function(by_python) + + +_FINITE = cs.float_schema(strict=True, allow_inf_nan=False) +_NOT_FINITE_READ = cs.no_info_after_validator_function( + _NOT_FINITE.__getitem__, cs.literal_schema(list(_NOT_FINITE)) +) diff --git a/tests/performance.py b/tests/performance.py index 5f0b073..7b29a07 100644 --- a/tests/performance.py +++ b/tests/performance.py @@ -68,11 +68,15 @@ def an_order(number): """ -def _measure(root: str, python_descriptors: bool) -> dict[str, float]: +def _measure(root: str, how: str) -> dict[str, float]: """The seconds each takes, in this process: which has the mode it was started with""" # Before this directory, whose schemas have no extensions sys.path.insert(0, root) - if python_descriptors: + if how == "alone": + # As where pydantic is not installed, which else writes and reads the JSON of what is held in Python + codec = import_module("dataclass_native._json") + codec._by_pydantic = lambda tp: None # pyright: ignore[reportAttributeAccessIssue] + if how == "descriptors": # As an extension built before it had its own: so before any class is bound to it for module in ("common", "trades", "mutable", "arrays"): try: @@ -120,8 +124,9 @@ def _rust() -> Path: return root -def _row(label: str, times: list[float], unit: float, places: int) -> str: - return f"| {label} | " + " | ".join(f"{t / unit:,.{places}f}" for t in times) + " |" +def _row(label: str, times: list[float | None], unit: float, places: int) -> str: + cells = ("" if t is None else f"{t / unit:,.{places}f}" for t in times) + return f"| {label} | " + " | ".join(cells) + " |" def main(): @@ -130,16 +135,17 @@ def main(): # Each in a process of its own, as a process has one mode rust = _rust() configurations = { - "`pure`": (Mode.PURE, TESTS, ""), + "`pure`": (Mode.PURE, TESTS, "alone"), + "`pure`, with pydantic": (Mode.PURE, TESTS, ""), "C++": (Mode.STRICT, BUILD / "src", ""), "Rust": (Mode.STRICT, rust, ""), - "C++, Python's descriptors": (Mode.STRICT, BUILD / "src", "python"), - "Rust, Python's descriptors": (Mode.STRICT, rust, "python"), + "C++, Python's descriptors": (Mode.STRICT, BUILD / "src", "descriptors"), + "Rust, Python's descriptors": (Mode.STRICT, rust, "descriptors"), } times = {} - for name, (mode, root, descriptors) in configurations.items(): + for name, (mode, root, how) in configurations.items(): result = subprocess.run( - [sys.executable, __file__, str(root), descriptors], + [sys.executable, __file__, str(root), how], env=os.environ | {ENV_VAR: mode}, capture_output=True, text=True, @@ -147,10 +153,12 @@ def main(): ) times[name] = json.loads(result.stdout) - print("| Nanoseconds to | " + " | ".join(times) + " |") - print("|---|" + "---:|" * len(times)) + # Which pydantic has no part in + objects = {name: of for name, of in times.items() if "pydantic" not in name} + print("| Nanoseconds to | " + " | ".join(objects) + " |") + print("|---|" + "---:|" * len(objects)) for label, statement in OBJECTS.items(): - print(_row(label, [of[statement] for of in times.values()], 1e-9, 0)) + print(_row(label, [of[statement] for of in objects.values()], 1e-9, 0)) # Which the descriptors have no part in written = {name: of for name, of in times.items() if "descriptors" not in name} @@ -159,11 +167,15 @@ def main(): for name, (write, read) in WRITTEN.items(): unit = 1e-6 * (ORDERS if name == "Arrow" else 1) for label, statement in ((f"Write {name}", write), (f"Read {name}", read)): - print(_row(label, [of[statement] for of in written.values()], unit, 1)) + cells = [ + None if "pydantic" in column and name != "JSON" else of[statement] + for column, of in written.items() + ] + print(_row(label, cells, unit, 1)) if __name__ == "__main__": if len(sys.argv) > 1: - print(json.dumps(_measure(sys.argv[1], sys.argv[2] == "python"))) + print(json.dumps(_measure(sys.argv[1], sys.argv[2]))) else: main() diff --git a/tests/test_json.py b/tests/test_json.py index e793ba5..c204d1a 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -1,13 +1,17 @@ """ The JSON format of JSON_FORMAT.md, as written and read in Python, and as pydantic reads and writes it. Run in pure -mode, and by test_bindings in strict and mixed modes. +mode, and by test_bindings in strict and mixed modes: and again by test_json_in_python, as what is held in Python is +here written and read by pydantic, which is installed where this is tested. """ import datetime as dt import json import math +import sys +import warnings from collections.abc import Mapping from decimal import Decimal +from types import MappingProxyType from typing import Annotated, Any from uuid import UUID @@ -35,9 +39,16 @@ mode, to_json, ) +from dataclass_native import _json as codec from dataclass_native._json import read, write from dataclass_native.schema import SchemaError + +def _by_pydantic(tp: Any) -> bool: + """Whether pydantic writes and reads the type: which is then as JSON_FORMAT.md says of it""" + return codec._by_pydantic(tp) is not None + + UTC = dt.UTC PARIS = dt.timezone(dt.timedelta(hours=1)) Price = Annotated[Decimal, DecimalPlaces(2)] @@ -120,7 +131,13 @@ @pytest.mark.parametrize(("tp", "value", "text"), VALUES) def test_values(tp, value, text): # As UTF-8 - assert to_json(value, tp) == text.encode() + written = to_json(value, tp) + if tp in (float, dt.timedelta) and _by_pydantic(tp): + # A float as its version writes one, and a timedelta of a year or more with its years + assert read(tp, written) == value + else: + assert written == text.encode() + assert write(value, tp) == text.encode() result = from_json(tp, text) assert result == value and type(result) is type(value) assert from_json(tp, text.encode()) == value @@ -134,9 +151,12 @@ def _round_trip(value: Any) -> Any: assert result == value # What is written depends only on the value assert to_json(result) == data - # The implementation in Python, which that used may not be, writes and reads the same - assert write(value) == data + # The implementation in Python, which that used may not be, reads the same, and what it writes is read the same assert read(type(value), data) == value + assert from_json(type(value), write(value)) == value + if not _by_pydantic(type(value)): + # And it writes the same: as pydantic does but a float, and a timedelta of a year or more + assert write(value) == data return result @@ -352,12 +372,23 @@ def test_invalid_data(tp, text): from_json(tp, text) +# A key twice +TWICE = '{"a": 1, "a": 2}' + + @pytest.mark.parametrize( - "text", ["", "{", "[1,]", "NaN", "[Infinity]", '{"a": 1, "a": 2}', "1 2", "'a'"] + "text", ["", "{", "[1,]", "NaN", "[Infinity]", TWICE, "1 2", "'a'"] ) def test_data_which_is_not_json(text): + tp = Mapping[str, int] with pytest.raises(ValueError, match="The data is not JSON: "): - from_json(Mapping[str, int], text) + read(tp, text) + if text == TWICE and _by_pydantic(tp): + # Of which pydantic reads the last + assert from_json(tp, text) == {"a": 2} + else: + with pytest.raises(ValueError, match="The data is not JSON: "): + from_json(tp, text) @pytest.mark.parametrize( @@ -382,11 +413,121 @@ def test_data_which_is_not_json(text): # Which would be read as the string it is written as (float | str, math.nan), (Money, Party("Acme", "LEI1", 3)), + # Which pydantic would write: as null, or as what it takes them for + (str, None), + (float, None), + (bool, None), + (dt.date, None), + (dt.timedelta, None), + (UUID, None), + (Side, None), + (int | str, None), + (tuple[str, ...], ("a", None)), + (tuple[float, ...], None), + (frozenset[str], frozenset({None})), + (Mapping[str, str], {"a": None}), + (Mapping[str, Money], {"a": None}), + (float, True), + (float, Decimal("1.5")), + (float, np.float64(1.5)), + (tuple[float, ...], (1.5, False)), + (bool, 1), + (str, Level.HIGH), + (dt.date, dt.datetime(2026, 1, 2)), + (tuple[int, str], (1, "a", 2)), + (int | str, 1.5), + (DiscriminatedUnion[str, bytes], 1), ], ) def test_invalid_values(tp, value): - with pytest.raises(TypeError, match="cannot be "): - to_json(value, tp) + with warnings.catch_warnings(record=True) as warned: + warnings.simplefilter("always") + with pytest.raises(TypeError, match="cannot be "): + to_json(value, tp) + # As pydantic does, of a value which it wrote as whatever it is + assert not warned + + +def test_values_which_are_not_of_the_type_exactly(): + # An int is written as the float it is: and as an int, where it may be either + assert to_json(1, float) == to_json(1, float | str) == b"1.0" + assert to_json((1, 2.5), tuple[float, ...]) == b"[1.0,2.5]" + assert to_json(1, float | int) == b"1" and to_json(1.0, float | int) == b"1.0" + # An enum's member may be given as its value, and a mapping be of any kind + assert to_json(2, Currency) == b"2" + assert to_json(MappingProxyType({"b": 1, "a": 2}), Mapping[str, int]) == ( + b'{"a":2,"b":1}' + ) + # A datetime is written in UTC, and read as in it, whatever its offset + there = dt.datetime(2026, 1, 2, 3, 4, 5, tzinfo=PARIS) + assert to_json((there,), tuple[dt.datetime, ...]) == b'["2026-01-02T02:04:05Z"]' + read_ = from_json(dt.datetime, '"2026-01-02T03:04:05+01:00"') + assert read_ == there and read_.tzinfo is UTC + + +def test_pydantic_need_not_be_installed(monkeypatch): + # As an import of it then fails + monkeypatch.setitem(sys.modules, "dataclass_native._pydantic", None) + monkeypatch.setattr(codec, "_by_pydantic", codec._pydantic_codec()) + assert not _by_pydantic(int) + assert to_json((1, 2), tuple[int, ...]) == b"[1,2]" + assert from_json(tuple[int, ...], "[1,2]") == (1, 2) + + +def test_pydantic_writes_and_reads_what_is_held_in_python(make_module): + """Where it may: which test_json_in_python has it not, so each of these is also of the Python alone""" + from dataclass_native._pydantic import codec as by_pydantic + + # A type of no class, in any mode + assert by_pydantic(tuple[int, ...]) and by_pydantic(Mapping[str, float] | None) + # Not what cannot be written, which the Python says: nor a type which has no hash, if any is given + assert by_pydantic(Trade) is None and by_pydantic([int]) is None + if mode() is not Mode.PURE: + return + # A class held in Python, but one which validates what it is made from + assert by_pydantic(Order) and by_pydantic(Everything) + assert by_pydantic(Account) is None and by_pydantic(tuple[Holder, ...]) is None + + module = make_module(""" + from dataclasses import dataclass, field + from dataclass_native import native + from schemas.mutable import Address + + @native + @dataclass + class Counted: + name: str + tags: tuple[str, ...] = field(default_factory=tuple) + where: Address = Address("London") + + def __post_init__(self): + self.made = True + + @native + @dataclass(frozen=True) + class Sized: + name: str + size: int = field(default=3, init=False) + + class Flat(Address): + pass + """) + # One is made as Python makes it: with its defaults, and what it does once made + counted = from_json(module.Counted, '{"name": "a", "other": 1}') + assert counted == module.Counted("a") and counted.made and counted.tags == () + assert counted.where is module.Counted.where + # Which pydantic does not, of a class with a field that it is not made from + assert by_pydantic(module.Counted) and by_pydantic(module.Sized) is None + sized = module.Sized("a") + assert from_json(module.Sized, to_json(sized)[:11] + b"}") == sized + # A subclass is another class + for value, tp in ( + (module.Flat("x"), Address), + (Customer("ann", module.Flat("x")), Customer), + (module.Counted("a", where=module.Flat("x")), None), + ): + with pytest.raises(TypeError, match="cannot be "): + to_json(value, tp) @pytest.mark.parametrize( @@ -553,12 +694,10 @@ def test_every_scalar(): "10", ] assert made["by_currency"] == {"1": "buy", "3": "sell"} and made["currency"] == 3 - # As Python writes a float - assert ( - to_json(value).count(b'[1.0,"Infinity",-0.0,5e-324,1.2345678901234568e+17,') - == 1 - ) - assert b"1000000000000000.0,1e+16,0.0001,1e-05]" in to_json(value) + # As Python writes a float: but by pydantic, which writes one as its version does + written = write(value) if _by_pydantic(Everything) else to_json(value) + assert written.count(b'[1.0,"Infinity",-0.0,5e-324,1.2345678901234568e+17,') == 1 + assert b"1000000000000000.0,1e+16,0.0001,1e-05]" in written _round_trip(value) _round_trip(Everything()) for either in (dt.datetime(2026, 1, 2, tzinfo=UTC), 2.5, math.inf, None): @@ -850,6 +989,10 @@ def test_every_scalar(): } +# Those of by_text with a key twice +KEY_TWICE = ('{"a": "b", "a": "c"}', '{"\\u0061": "b", "a": "c"}') + + def _outcome(reading: Any, text: str | bytes) -> bytes | None: """What was read, as it is written: or None if it was not read""" try: @@ -864,6 +1007,11 @@ def _outcome(reading: Any, text: str | bytes) -> bytes | None: def test_both_read_the_same(name, fragment): # Within what is ignored, and of any spacing text = f' {{"other": [{{"a": null}}, 1e5], "{name}" :\n{fragment} }}' + if fragment in KEY_TWICE and _by_pydantic(Everything): + # Which the Python does not read: of which pydantic reads the last + assert from_json(Everything, text).by_text == {"a": "c"} + assert _outcome(read, text) is None + return # The implementation in Python, which that used may not be, reads the same or neither does assert _outcome(from_json, text) == _outcome(read, text) assert _outcome(from_json, text.encode()) == _outcome(read, text) diff --git a/tests/test_json_in_python.py b/tests/test_json_in_python.py new file mode 100644 index 0000000..8ba722f --- /dev/null +++ b/tests/test_json_in_python.py @@ -0,0 +1,14 @@ +""" +The tests of test_json again, with what is held in Python written and read by the Python alone: as it is where +pydantic is not installed +""" + +import pytest +from test_json import * + +from dataclass_native import _json as codec + + +@pytest.fixture(autouse=True) +def in_python(monkeypatch): + monkeypatch.setattr(codec, "_by_pydantic", lambda tp: None) diff --git a/uv.lock b/uv.lock index 87f8740..8292d3a 100644 --- a/uv.lock +++ b/uv.lock @@ -166,6 +166,9 @@ arrow = [ numpy = [ { name = "numpy" }, ] +pydantic = [ + { name = "pydantic" }, +] [package.dev-dependencies] dev = [ @@ -188,9 +191,10 @@ requires-dist = [ { name = "jinja2", specifier = ">=3.1.6" }, { 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 = "tzdata", marker = "sys_platform == 'win32' and extra == 'arrow'", specifier = ">=2026.6" }, ] -provides-extras = ["numpy", "arrow"] +provides-extras = ["numpy", "pydantic", "arrow"] [package.metadata.requires-dev] dev = [