pydantic-addons 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.
@@ -0,0 +1,21 @@
1
+ """
2
+ Annotations which pydantic reads and writes, without depending on it: to a type checker each is the type it
3
+ annotates, and pydantic is imported only when it asks one how to read and write it.
4
+ """
5
+
6
+ from ._version import __version__
7
+ from .discriminated_union import DISCRIMINATED, DiscriminatedMarker, DiscriminatedUnion
8
+ from .shared import SHARED, Shared, SharedMarker
9
+ from .tags import tag, tagged
10
+
11
+ __all__ = [
12
+ "DISCRIMINATED",
13
+ "SHARED",
14
+ "DiscriminatedMarker",
15
+ "DiscriminatedUnion",
16
+ "Shared",
17
+ "SharedMarker",
18
+ "__version__",
19
+ "tag",
20
+ "tagged",
21
+ ]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '1.0.0'
22
+ __version_tuple__ = version_tuple = (1, 0, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,120 @@
1
+ """
2
+ DiscriminatedUnion[A, B, ...]: a union whose value is written with a tag, which says which member it is of:
3
+
4
+ {"t": tag, "v": value}
5
+
6
+ So members which are written alike, as two classes of the same fields are, are told apart when read. The tags are
7
+ those of tags.tag.
8
+
9
+ It is Annotated[A | B, DISCRIMINATED], so whatever reads annotations finds the marker in the metadata, and the
10
+ members in the union. pydantic is one such, which the marker tells how to read and write it.
11
+ """
12
+
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Annotated,
16
+ Any,
17
+ TypeAliasType,
18
+ Union,
19
+ get_args,
20
+ get_origin,
21
+ )
22
+
23
+ from .tags import tag
24
+
25
+
26
+ class DiscriminatedMarker:
27
+ """Annotated metadata marking a union as discriminated"""
28
+
29
+ def __repr__(self) -> str:
30
+ return "Discriminated"
31
+
32
+ def __get_pydantic_core_schema__(self, source: Any, handler: Any) -> Any:
33
+ # Here, so that pydantic is imported only if it asks
34
+ from pydantic_core import core_schema as cs
35
+
36
+ members = get_args(source)
37
+ tags = [tag(member) for member in members]
38
+ if len(set(tags)) < len(tags):
39
+ raise TypeError(
40
+ f"The members of DiscriminatedUnion{list(members)} do not each have a tag of their own: {tags}"
41
+ )
42
+ schemas = [handler.generate_schema(member) for member in members]
43
+
44
+ def tagged(entries: Any, **how: Any) -> Any:
45
+ return cs.tagged_union_schema(
46
+ {
47
+ name: entries(
48
+ {"t": how["field"](cs.str_schema()), "v": how["field"](schema)},
49
+ extra_behavior="forbid",
50
+ )
51
+ for name, schema in zip(tags, schemas, strict=True)
52
+ },
53
+ "t",
54
+ )
55
+
56
+ # Read as the fields of a model are, which have the configuration of what holds them: as those of a
57
+ # typed dict, which has its own, do not. So that bytes, say, are read as the model reads them
58
+ read = cs.no_info_after_validator_function(
59
+ _value, tagged(cs.model_fields_schema, field=cs.model_field)
60
+ )
61
+
62
+ # The tag of a value is that of the member whose class it is of: exactly, as a subclass is another type,
63
+ # with a tag of its own
64
+ by_class: dict[Any, str] = {}
65
+ for member, name in zip(members, tags, strict=True):
66
+ by_class.setdefault(_class(member), name)
67
+
68
+ def with_tag(value: Any) -> dict[str, Any]:
69
+ if name := by_class.get(type(value)):
70
+ return {"t": name, "v": value}
71
+ if type(value) is int and float in by_class:
72
+ # An int is the float it is, where it may not be an int
73
+ return {"t": by_class[float], "v": float(value)}
74
+ raise TypeError(
75
+ f"{value!r} is of no member of DiscriminatedUnion{list(members)}"
76
+ )
77
+
78
+ return cs.json_or_python_schema(
79
+ json_schema=read,
80
+ # In Python, also a value of a member, as itself
81
+ python_schema=cs.union_schema(
82
+ [read, handler(source)], mode="left_to_right"
83
+ ),
84
+ serialization=cs.plain_serializer_function_ser_schema(
85
+ with_tag,
86
+ return_schema=tagged(cs.typed_dict_schema, field=cs.typed_dict_field),
87
+ ),
88
+ )
89
+
90
+
91
+ def _value(read: tuple[dict[str, Any], Any, Any]) -> Any:
92
+ """The value of what was read as fields: which are given with what else a model has"""
93
+ return read[0]["v"]
94
+
95
+
96
+ def _class(member: Any) -> Any:
97
+ """The class whose instances are values of a member: that annotated or named, or which a generic is of"""
98
+ while True:
99
+ if get_origin(member) is Annotated:
100
+ member = get_args(member)[0]
101
+ elif isinstance(member, TypeAliasType):
102
+ member = member.__value__
103
+ else:
104
+ return get_origin(member) or member
105
+
106
+
107
+ DISCRIMINATED = DiscriminatedMarker()
108
+
109
+ if TYPE_CHECKING:
110
+ # For type checkers, a union of its members
111
+ DiscriminatedUnion = Union
112
+ else:
113
+
114
+ class DiscriminatedUnion:
115
+ """A union written as {"t": tag, "v": value}, the tag naming the member's type"""
116
+
117
+ def __class_getitem__(cls, params):
118
+ if not isinstance(params, tuple) or len(params) < 2:
119
+ raise TypeError("DiscriminatedUnion needs at least two types")
120
+ return Annotated[Union[params], DISCRIMINATED] # noqa: UP007
File without changes
@@ -0,0 +1,24 @@
1
+ """
2
+ Shared[A]: the value is shared with whatever else holds it, not a copy of its own.
3
+
4
+ It is Annotated[A, SHARED], so whatever reads annotations finds the marker in the metadata, and says what being
5
+ shared is to it: as dataclass-native holds one natively by a pointer which counts its references, and writes it once
6
+ for all that share it. To pydantic, which the marker tells nothing, it is A: validated and written as the value.
7
+ """
8
+
9
+ from typing import Annotated, TypeVar
10
+
11
+
12
+ class SharedMarker:
13
+ """Annotated metadata marking a value as shared"""
14
+
15
+ def __repr__(self) -> str:
16
+ return "Shared"
17
+
18
+
19
+ SHARED = SharedMarker()
20
+
21
+ T = TypeVar("T")
22
+
23
+ Shared = Annotated[T, SHARED]
24
+ """The value is shared, not copied: Shared[A], Shared[A | B], Shared[A] | None"""
@@ -0,0 +1,54 @@
1
+ """
2
+ The tag which names a type, where what is written of a value says which type it is of: as a DiscriminatedUnion
3
+ has it.
4
+ """
5
+
6
+ from collections.abc import Callable
7
+ from dataclasses import is_dataclass
8
+ from enum import Enum
9
+ from typing import Annotated, Any, TypeAliasType, get_args, get_origin
10
+ from weakref import WeakKeyDictionary
11
+
12
+ # The tag given to a class: not to its subclasses, each of which is a type of its own
13
+ _given: WeakKeyDictionary[type, str] = WeakKeyDictionary()
14
+
15
+
16
+ def tagged[C: type](name: str) -> Callable[[C], C]:
17
+ """
18
+ Gives a class the tag which names it, in place of its module and qualified name: so that it may be moved or
19
+ renamed, and what was written of it still be read.
20
+ """
21
+
22
+ def decorate(cls: C) -> C:
23
+ _given[cls] = name
24
+ return cls
25
+
26
+ return decorate
27
+
28
+
29
+ def tag(tp: Any) -> str:
30
+ """
31
+ The tag of a type:
32
+
33
+ - A class which was given one by @tagged: that
34
+ - Any other dataclass, enum or pydantic model: its module and qualified name, as "trades.Bond". These are a
35
+ program's own, of which two may have the same name
36
+ - Annotated[T, ...]: the __tag__ of the first of its metadata which has one, as an annotation of a size of int
37
+ may: else the tag of T
38
+ - A name given to a type, by a type statement: the tag of that type
39
+ - Anything else: its name, in lower case, as "int", "datetime" and "uuid"
40
+ """
41
+ if isinstance(tp, TypeAliasType):
42
+ return tag(tp.__value__)
43
+ if get_origin(tp) is Annotated:
44
+ inner, *metadata = get_args(tp)
45
+ for item in metadata:
46
+ if own := getattr(item, "__tag__", None):
47
+ return own
48
+ return tag(inner)
49
+ if isinstance(tp, type):
50
+ if given := _given.get(tp):
51
+ return given
52
+ if is_dataclass(tp) or issubclass(tp, Enum) or hasattr(tp, "model_fields"):
53
+ return f"{tp.__module__}.{tp.__qualname__}"
54
+ return getattr(tp, "__name__", str(tp)).lower()
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydantic-addons
3
+ Version: 1.0.0
4
+ Summary: Annotations which pydantic reads and writes, without depending on it: DiscriminatedUnion and Shared
5
+ Author-email: Nick Young <nick.young.github@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Nick Young
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Classifier: License :: OSI Approved :: MIT License
29
+ Classifier: Programming Language :: Python :: 3
30
+ Classifier: Programming Language :: Python :: 3 :: Only
31
+ Classifier: Programming Language :: Python :: 3.13
32
+ Classifier: Programming Language :: Python :: 3.14
33
+ Classifier: Operating System :: OS Independent
34
+ Requires-Python: >=3.13
35
+ Description-Content-Type: text/markdown
36
+ License-File: LICENSE
37
+ Dynamic: license-file
38
+
39
+ # pydantic-addons
40
+
41
+ Annotations for the fields of dataclasses and models, which [pydantic](https://docs.pydantic.dev) reads and
42
+ writes, and which do not depend on it. To a type checker each is the type it annotates. pydantic is imported only
43
+ when it asks an annotation how to read and write it, so a library may use them, and read them for itself, whether
44
+ or not pydantic is installed: as [dataclass-native](https://github.com/nickyoung-github/dataclass-native) does.
45
+
46
+ ```
47
+ pip install pydantic-addons
48
+ ```
49
+
50
+ Python 3.13 or later.
51
+
52
+ ## DiscriminatedUnion
53
+
54
+ A union whose value is written with a tag, which says which member it is of. So members which are written alike
55
+ are told apart when read: as two classes of the same fields are not, by a plain union.
56
+
57
+ ```python
58
+ from dataclasses import dataclass
59
+
60
+ from pydantic import TypeAdapter
61
+ from pydantic_addons import DiscriminatedUnion
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Cash:
66
+ amount: float
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Bond:
71
+ amount: float
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Trade:
76
+ instrument: DiscriminatedUnion[Cash, Bond]
77
+
78
+
79
+ adapter = TypeAdapter(Trade)
80
+ adapter.dump_json(Trade(Bond(1.5)))
81
+ # b'{"instrument":{"t":"trades.Bond","v":{"amount":1.5}}}'
82
+ adapter.validate_json('{"instrument":{"t":"trades.Bond","v":{"amount":1.5}}}')
83
+ # Trade(instrument=Bond(amount=1.5))
84
+ ```
85
+
86
+ - It is written as `{"t": tag, "v": value}`, and read from that with its entries in either order. In Python, a
87
+ value of a member is also validated as itself.
88
+ - A value is to be of a member exactly. A subclass of a member's is another type, with a tag of its own, so is
89
+ not written unless it is itself a member: nor is a `bool` as an `int`. An `int` is written as the `float` it
90
+ is, where it may not be an `int`.
91
+ - The members are to have tags of their own.
92
+
93
+ ### Tags
94
+
95
+ | Type | Tag |
96
+ |---|---|
97
+ | a class given one by `@tagged` | that |
98
+ | any other dataclass, enum or pydantic model | its module and qualified name: `"trades.Bond"` |
99
+ | `Annotated[T, ...]` | the `__tag__` of the first of its metadata which has one: else the tag of `T` |
100
+ | a name given to a type, as `type Price = ...` | the tag of that type |
101
+ | anything else | its name, in lower case: `"int"`, `"datetime"`, `"uuid"` |
102
+
103
+ `tag(tp)` gives the tag of a type. Give a class a tag of its own so that it may be moved or renamed, and what
104
+ was written of it still be read:
105
+
106
+ ```python
107
+ from pydantic_addons import tagged
108
+
109
+
110
+ @tagged("bond.v1")
111
+ @dataclass(frozen=True)
112
+ class Bond:
113
+ amount: float
114
+ ```
115
+
116
+ A subclass does not have the tag its base was given: it is another type.
117
+
118
+ ## Shared
119
+
120
+ `Shared[A]` says that the value is shared with whatever else holds it, not a copy of its own: `Shared[A]`,
121
+ `Shared[A | B]`, `Shared[A] | None`.
122
+
123
+ What that is, is for whatever reads the annotation to say. dataclass-native holds a shared object natively by a
124
+ pointer which counts its references, and writes it once for all that share it. To pydantic it is `A`: validated
125
+ and written as the value, wherever it is held.
126
+
127
+ ## Reading the annotations
128
+
129
+ Each is `Annotated`, with a marker in its metadata: `DISCRIMINATED`, a `DiscriminatedMarker`, on the union of
130
+ the members, and `SHARED`, a `SharedMarker`, on the type.
131
+
132
+ ```python
133
+ from typing import get_args
134
+
135
+ from pydantic_addons import DISCRIMINATED, SHARED, DiscriminatedUnion, Shared
136
+
137
+ get_args(DiscriminatedUnion[Cash, Bond]) # (Cash | Bond, DISCRIMINATED)
138
+ get_args(Shared[Cash]) # (Cash, SHARED)
139
+ ```
140
+
141
+ ## Development
142
+
143
+ ```
144
+ uv sync
145
+ uv run pre-commit install
146
+ uv run pytest
147
+ ```
148
+
149
+ A release is a tag `v1.2.3`, which is its version: the release workflow builds it and publishes it to PyPI.
@@ -0,0 +1,11 @@
1
+ pydantic_addons/__init__.py,sha256=-ANvDxX-O2VOE7L71ezvtPtVwKsMPB3RbDvWqtk11z0,583
2
+ pydantic_addons/_version.py,sha256=JAAyU3al4wmBf3BF-Umm1J_GrCIT-yS_yWEGHqKRVHc,520
3
+ pydantic_addons/discriminated_union.py,sha256=ASwVggD161RmRK5irbBPXbVch-4tSYjGXhURuFgPMyg,4438
4
+ pydantic_addons/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pydantic_addons/shared.py,sha256=7Ms0R6YhopsY8PEKg3hwwZ9pMZ5HACoXlGbsSLAVlCc,763
6
+ pydantic_addons/tags.py,sha256=l7VhTOcCYQ3CXpHu_sT29POTLzHL7qTyW3NVlwpmNDE,1962
7
+ pydantic_addons-1.0.0.dist-info/licenses/LICENSE,sha256=Sqb5PaNhM-_U75tuToUj8ONWfUsSV5seXsF73n9ni3o,1067
8
+ pydantic_addons-1.0.0.dist-info/METADATA,sha256=zxxKgc2q-xA_dzIz3PhTZyfnNeIVqtAc1eKBrgst4bw,5481
9
+ pydantic_addons-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ pydantic_addons-1.0.0.dist-info/top_level.txt,sha256=foAOIzKs2dhLOOW_4xrzFw-vauzhoOVOuar310qx9cE,16
11
+ pydantic_addons-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nick Young
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pydantic_addons