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
20 changes: 20 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions JSON_FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
23 changes: 13 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
32 changes: 31 additions & 1 deletion src/dataclass_native/_json.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)


Expand All @@ -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)
Expand Down
Loading
Loading