pydantic-jsonpointer 0.1.0b1__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.
- pydantic_jsonpointer/__init__.py +62 -0
- pydantic_jsonpointer/__version__.py +1 -0
- pydantic_jsonpointer/_model_path.py +379 -0
- pydantic_jsonpointer/adapters.py +313 -0
- pydantic_jsonpointer/errors.py +47 -0
- pydantic_jsonpointer/mypy_plugin.py +849 -0
- pydantic_jsonpointer/py.typed +0 -0
- pydantic_jsonpointer/pydantic_adapter.py +333 -0
- pydantic_jsonpointer/traversal.py +345 -0
- pydantic_jsonpointer/types.py +117 -0
- pydantic_jsonpointer-0.1.0b1.dist-info/METADATA +104 -0
- pydantic_jsonpointer-0.1.0b1.dist-info/RECORD +13 -0
- pydantic_jsonpointer-0.1.0b1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Container adapter Protocol and registry.
|
|
2
|
+
|
|
3
|
+
A ContainerAdapter teaches the traversal layer how to read/write a specific
|
|
4
|
+
container type. The registry maps runtime types to adapter instances, with
|
|
5
|
+
MRO-aware lookup so subclasses inherit registration.
|
|
6
|
+
|
|
7
|
+
`unwrap()` uses the built-in `Ellipsis` singleton (`...`) as its "no unwrap"
|
|
8
|
+
return marker. Adapters MUST return `...` to mean "use the value as-is";
|
|
9
|
+
returning a real Ellipsis payload (e.g. a RootModel wrapping `Ellipsis`)
|
|
10
|
+
would be indistinguishable from "no unwrap". This is a documented constraint
|
|
11
|
+
on adapter authors; the practical impact is nil because no real document
|
|
12
|
+
contains `...`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import Any, Protocol, TypeGuard, runtime_checkable
|
|
18
|
+
|
|
19
|
+
from .errors import (
|
|
20
|
+
AdapterNotFoundError,
|
|
21
|
+
ImmutableTargetError,
|
|
22
|
+
InvalidTokenError,
|
|
23
|
+
PointerNotFoundError,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _is_ascii_digits(s: str) -> bool:
|
|
28
|
+
"""True iff ``s`` is a non-empty sequence of ASCII ``0``-``9`` characters."""
|
|
29
|
+
return bool(s) and all("0" <= c <= "9" for c in s)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_int_index(key: Any) -> TypeGuard[int]:
|
|
33
|
+
"""True iff ``key`` is a real int (rejects ``bool`` since ``True``/``False``
|
|
34
|
+
would otherwise be accepted as valid indices via ``isinstance(True, int)``).
|
|
35
|
+
"""
|
|
36
|
+
return isinstance(key, int) and not isinstance(key, bool)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@runtime_checkable
|
|
40
|
+
class ContainerAdapter(Protocol):
|
|
41
|
+
"""Per-type strategy for reading/writing a container at a JSON-pointer key.
|
|
42
|
+
|
|
43
|
+
Every public method receives `parent` (the container) and (for non-resolve
|
|
44
|
+
methods) `key` (already coerced via resolve_token). Adapters are expected
|
|
45
|
+
to be stateless — they are shared across calls.
|
|
46
|
+
|
|
47
|
+
`unwrap` returns `...` (Ellipsis) to mean "no unwrap; use value as-is",
|
|
48
|
+
or the inner value to substitute transparently.
|
|
49
|
+
|
|
50
|
+
Adapters may OPTIONALLY define ``is_value_frozen(value) -> bool``: when
|
|
51
|
+
present, the walker treats it as an additional taint source so that an
|
|
52
|
+
immutable wrapper (e.g. a frozen ``RootModel``) propagates the freeze
|
|
53
|
+
bit through ``unwrap`` to its inner payload. Adapters that omit the hook
|
|
54
|
+
— including any third-party adapter written against the canonical
|
|
55
|
+
8-method contract — are treated as if it returned False. The hook is
|
|
56
|
+
deliberately outside the required Protocol surface so legacy adapters
|
|
57
|
+
keep satisfying ``isinstance(adapter, ContainerAdapter)`` and static
|
|
58
|
+
type-checks against ``register()``.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def resolve_token(self, parent: Any, raw_token: str) -> int | str: ...
|
|
62
|
+
def has(self, parent: Any, key: int | str) -> bool: ...
|
|
63
|
+
def get(self, parent: Any, key: int | str) -> Any: ...
|
|
64
|
+
def set(self, parent: Any, key: int | str, value: Any) -> None: ...
|
|
65
|
+
def add(self, parent: Any, key: int | str, value: Any) -> None: ...
|
|
66
|
+
def remove(self, parent: Any, key: int | str) -> Any: ...
|
|
67
|
+
def unwrap(self, value: Any) -> Any: ...
|
|
68
|
+
def is_step_frozen(self, parent: Any, key: int | str) -> bool: ...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_REGISTRY: dict[type, ContainerAdapter] = {}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def register(
|
|
75
|
+
container_type: type,
|
|
76
|
+
adapter: ContainerAdapter,
|
|
77
|
+
*,
|
|
78
|
+
override: bool = False,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Register `adapter` as the handler for `container_type`.
|
|
81
|
+
|
|
82
|
+
Subsequent `adapter_for(value)` calls return `adapter` when
|
|
83
|
+
`type(value)` is `container_type` or a subclass of it (via MRO walk).
|
|
84
|
+
|
|
85
|
+
Raises ValueError if the type is already registered unless override=True.
|
|
86
|
+
"""
|
|
87
|
+
if not override and container_type in _REGISTRY:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
f"adapter already registered for {container_type!r}; "
|
|
90
|
+
f"pass override=True to replace it"
|
|
91
|
+
)
|
|
92
|
+
_REGISTRY[container_type] = adapter
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def adapter_for(value: Any, *, resolver: Any = None) -> ContainerAdapter:
|
|
96
|
+
"""Look up the adapter for `type(value)` via MRO walk.
|
|
97
|
+
|
|
98
|
+
If `resolver` is provided AND the resolved adapter is a
|
|
99
|
+
``BaseModelAdapter`` (or subclass), returns a per-call clone produced by
|
|
100
|
+
``adapter.with_resolver(resolver)`` — a shallow copy of the registered
|
|
101
|
+
instance with its resolver substituted. Subclass identity and any extra
|
|
102
|
+
state on the registered instance are preserved; subclasses with state
|
|
103
|
+
that needs custom cloning can override ``with_resolver``. The registered
|
|
104
|
+
adapter itself is never mutated.
|
|
105
|
+
|
|
106
|
+
Raises AdapterNotFoundError if no adapter is registered for any class
|
|
107
|
+
in the value's MRO.
|
|
108
|
+
"""
|
|
109
|
+
for cls in type(value).__mro__:
|
|
110
|
+
adapter = _REGISTRY.get(cls)
|
|
111
|
+
if adapter is not None:
|
|
112
|
+
if resolver is not None:
|
|
113
|
+
from .pydantic_adapter import BaseModelAdapter
|
|
114
|
+
|
|
115
|
+
if isinstance(adapter, BaseModelAdapter):
|
|
116
|
+
return adapter.with_resolver(resolver)
|
|
117
|
+
return adapter
|
|
118
|
+
raise AdapterNotFoundError(
|
|
119
|
+
f"no adapter registered for type {type(value).__name__!r}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class DictAdapter:
|
|
124
|
+
"""Adapter for built-in ``dict`` containers.
|
|
125
|
+
|
|
126
|
+
Tokens are used verbatim as keys (already RFC-6901-unescaped by JsonPointer).
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def resolve_token(self, parent: Any, raw_token: str) -> str:
|
|
130
|
+
return raw_token
|
|
131
|
+
|
|
132
|
+
def has(self, parent: Any, key: int | str) -> bool:
|
|
133
|
+
return key in parent
|
|
134
|
+
|
|
135
|
+
def get(self, parent: Any, key: int | str) -> Any:
|
|
136
|
+
try:
|
|
137
|
+
return parent[key]
|
|
138
|
+
except KeyError as exc:
|
|
139
|
+
raise PointerNotFoundError(repr(key)) from exc
|
|
140
|
+
|
|
141
|
+
def set(self, parent: Any, key: int | str, value: Any) -> None:
|
|
142
|
+
if key not in parent:
|
|
143
|
+
raise PointerNotFoundError(f"cannot replace {key!r}: key not present")
|
|
144
|
+
parent[key] = value
|
|
145
|
+
|
|
146
|
+
def add(self, parent: Any, key: int | str, value: Any) -> None:
|
|
147
|
+
parent[key] = value
|
|
148
|
+
|
|
149
|
+
def remove(self, parent: Any, key: int | str) -> Any:
|
|
150
|
+
try:
|
|
151
|
+
return parent.pop(key)
|
|
152
|
+
except KeyError as exc:
|
|
153
|
+
raise PointerNotFoundError(repr(key)) from exc
|
|
154
|
+
|
|
155
|
+
def unwrap(self, value: Any) -> Any:
|
|
156
|
+
return ...
|
|
157
|
+
|
|
158
|
+
def is_step_frozen(self, parent: Any, key: int | str) -> bool:
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
register(dict, DictAdapter())
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class ListAdapter:
|
|
166
|
+
"""Adapter for built-in ``list`` containers.
|
|
167
|
+
|
|
168
|
+
RFC 6901 array-index rules: the token must be either ``"-"`` (tail marker,
|
|
169
|
+
only valid for ``add``) or a run of decimal digits with no leading zero
|
|
170
|
+
(except the single-character ``"0"``).
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
DASH = "-"
|
|
174
|
+
|
|
175
|
+
def resolve_token(self, parent: Any, raw_token: str) -> int | str:
|
|
176
|
+
if raw_token == self.DASH:
|
|
177
|
+
return self.DASH
|
|
178
|
+
# RFC 6901 §4: array index tokens are ASCII decimal digits only.
|
|
179
|
+
# ``str.isdecimal`` would accept non-ASCII Unicode digits (e.g. Arabic-Indic).
|
|
180
|
+
if not raw_token or not _is_ascii_digits(raw_token):
|
|
181
|
+
raise InvalidTokenError(
|
|
182
|
+
f"invalid array index {raw_token!r}: "
|
|
183
|
+
"expected non-negative decimal or '-'"
|
|
184
|
+
)
|
|
185
|
+
if len(raw_token) > 1 and raw_token[0] == "0":
|
|
186
|
+
raise InvalidTokenError(
|
|
187
|
+
f"invalid array index {raw_token!r}: leading zero not permitted"
|
|
188
|
+
)
|
|
189
|
+
return int(raw_token)
|
|
190
|
+
|
|
191
|
+
def has(self, parent: Any, key: int | str) -> bool:
|
|
192
|
+
if not _is_int_index(key):
|
|
193
|
+
return False
|
|
194
|
+
return 0 <= key < len(parent)
|
|
195
|
+
|
|
196
|
+
def get(self, parent: Any, key: int | str) -> Any:
|
|
197
|
+
if key == self.DASH:
|
|
198
|
+
raise InvalidTokenError(
|
|
199
|
+
"cannot get '-': no element exists at the tail position"
|
|
200
|
+
)
|
|
201
|
+
if not _is_int_index(key):
|
|
202
|
+
raise InvalidTokenError(f"invalid array index {key!r}: expected int")
|
|
203
|
+
if not (0 <= key < len(parent)):
|
|
204
|
+
raise PointerNotFoundError(
|
|
205
|
+
f"list index {key} out of range (len={len(parent)})"
|
|
206
|
+
)
|
|
207
|
+
return parent[key]
|
|
208
|
+
|
|
209
|
+
def set(self, parent: Any, key: int | str, value: Any) -> None:
|
|
210
|
+
if key == self.DASH:
|
|
211
|
+
raise InvalidTokenError(
|
|
212
|
+
"cannot replace at '-': no element exists at the tail position"
|
|
213
|
+
)
|
|
214
|
+
if not _is_int_index(key):
|
|
215
|
+
raise InvalidTokenError(f"invalid array index {key!r}: expected int")
|
|
216
|
+
if not (0 <= key < len(parent)):
|
|
217
|
+
raise PointerNotFoundError(
|
|
218
|
+
f"list index {key} out of range (len={len(parent)})"
|
|
219
|
+
)
|
|
220
|
+
parent[key] = value
|
|
221
|
+
|
|
222
|
+
def add(self, parent: Any, key: int | str, value: Any) -> None:
|
|
223
|
+
if key == self.DASH:
|
|
224
|
+
parent.append(value)
|
|
225
|
+
return
|
|
226
|
+
if not _is_int_index(key):
|
|
227
|
+
raise InvalidTokenError(f"invalid array index {key!r}: expected int")
|
|
228
|
+
if not (0 <= key <= len(parent)):
|
|
229
|
+
raise InvalidTokenError(
|
|
230
|
+
f"list index {key} out of range for add (len={len(parent)})"
|
|
231
|
+
)
|
|
232
|
+
parent.insert(key, value)
|
|
233
|
+
|
|
234
|
+
def remove(self, parent: Any, key: int | str) -> Any:
|
|
235
|
+
if key == self.DASH:
|
|
236
|
+
raise InvalidTokenError(
|
|
237
|
+
"cannot remove '-': no element exists at the tail position"
|
|
238
|
+
)
|
|
239
|
+
if not _is_int_index(key):
|
|
240
|
+
raise InvalidTokenError(f"invalid array index {key!r}: expected int")
|
|
241
|
+
if not (0 <= key < len(parent)):
|
|
242
|
+
raise PointerNotFoundError(
|
|
243
|
+
f"list index {key} out of range (len={len(parent)})"
|
|
244
|
+
)
|
|
245
|
+
return parent.pop(key)
|
|
246
|
+
|
|
247
|
+
def unwrap(self, value: Any) -> Any:
|
|
248
|
+
return ...
|
|
249
|
+
|
|
250
|
+
def is_step_frozen(self, parent: Any, key: int | str) -> bool:
|
|
251
|
+
return False
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
register(list, ListAdapter())
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class TupleAdapter:
|
|
258
|
+
"""Adapter for built-in ``tuple`` containers (read-only).
|
|
259
|
+
|
|
260
|
+
Tuples are immutable: ``set``, ``add``, and ``remove`` all raise
|
|
261
|
+
``ImmutableTargetError``. ``is_step_frozen`` returns ``False`` so that
|
|
262
|
+
mutable objects *inside* a tuple slot remain writable via their own
|
|
263
|
+
adapters.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
def resolve_token(self, parent: Any, raw_token: str) -> int:
|
|
267
|
+
if not raw_token or not _is_ascii_digits(raw_token):
|
|
268
|
+
raise InvalidTokenError(
|
|
269
|
+
f"invalid tuple index {raw_token!r}: expected non-negative decimal"
|
|
270
|
+
)
|
|
271
|
+
if len(raw_token) > 1 and raw_token[0] == "0":
|
|
272
|
+
raise InvalidTokenError(
|
|
273
|
+
f"invalid tuple index {raw_token!r}: leading zero not permitted"
|
|
274
|
+
)
|
|
275
|
+
return int(raw_token)
|
|
276
|
+
|
|
277
|
+
def has(self, parent: Any, key: int | str) -> bool:
|
|
278
|
+
if not _is_int_index(key):
|
|
279
|
+
return False
|
|
280
|
+
return 0 <= key < len(parent)
|
|
281
|
+
|
|
282
|
+
def get(self, parent: Any, key: int | str) -> Any:
|
|
283
|
+
if not _is_int_index(key):
|
|
284
|
+
raise InvalidTokenError(f"invalid tuple index {key!r}: expected int")
|
|
285
|
+
if not (0 <= key < len(parent)):
|
|
286
|
+
raise PointerNotFoundError(
|
|
287
|
+
f"tuple index {key} out of range (len={len(parent)})"
|
|
288
|
+
)
|
|
289
|
+
return parent[key]
|
|
290
|
+
|
|
291
|
+
def set(self, parent: Any, key: int | str, value: Any) -> None:
|
|
292
|
+
if not _is_int_index(key):
|
|
293
|
+
raise InvalidTokenError(f"invalid tuple index {key!r}: expected int")
|
|
294
|
+
raise ImmutableTargetError("cannot modify tuple element: tuples are immutable")
|
|
295
|
+
|
|
296
|
+
def add(self, parent: Any, key: int | str, value: Any) -> None:
|
|
297
|
+
if not _is_int_index(key):
|
|
298
|
+
raise InvalidTokenError(f"invalid tuple index {key!r}: expected int")
|
|
299
|
+
raise ImmutableTargetError("cannot add to tuple: tuples are immutable")
|
|
300
|
+
|
|
301
|
+
def remove(self, parent: Any, key: int | str) -> Any:
|
|
302
|
+
if not _is_int_index(key):
|
|
303
|
+
raise InvalidTokenError(f"invalid tuple index {key!r}: expected int")
|
|
304
|
+
raise ImmutableTargetError("cannot remove from tuple: tuples are immutable")
|
|
305
|
+
|
|
306
|
+
def unwrap(self, value: Any) -> Any:
|
|
307
|
+
return ...
|
|
308
|
+
|
|
309
|
+
def is_step_frozen(self, parent: Any, key: int | str) -> bool:
|
|
310
|
+
return False
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
register(tuple, TupleAdapter())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Error types for pointer-traversal APIs.
|
|
2
|
+
|
|
3
|
+
Kept in a dedicated module so that the adapter layer (which must raise these)
|
|
4
|
+
can import them without depending on the traversal layer, which would create
|
|
5
|
+
an import cycle.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PointerError(Exception):
|
|
12
|
+
"""Base class for all pointer-traversal errors."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PointerNotFoundError(PointerError, KeyError):
|
|
16
|
+
"""Raised when a path step expects a value to exist and it does not.
|
|
17
|
+
|
|
18
|
+
Inherits from ``KeyError`` so callers can ``except KeyError``. ``__str__``
|
|
19
|
+
is overridden because ``KeyError.__str__`` calls ``repr`` on its single
|
|
20
|
+
arg, which would wrap our already human-readable messages in stray quotes
|
|
21
|
+
(e.g. ``"'missing key'"`` instead of ``missing key``).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
return Exception.__str__(self)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AdapterNotFoundError(PointerError, TypeError):
|
|
29
|
+
"""Raised when no ContainerAdapter is registered for a value's type."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class InvalidTokenError(PointerError, ValueError):
|
|
33
|
+
"""Raised when a token cannot be resolved against the current container
|
|
34
|
+
(e.g. non-decimal token for a list, unknown field name for a model)."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RootRebindError(PointerError):
|
|
38
|
+
"""Raised when set/add/remove is attempted on the root Ptr.
|
|
39
|
+
|
|
40
|
+
Python functions cannot rebind a caller's variable; callers must replace
|
|
41
|
+
the document themselves.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ImmutableTargetError(PointerError):
|
|
46
|
+
"""Raised when set/add/remove is attempted on a target that is under a
|
|
47
|
+
frozen binding (transitive). See BaseModelAdapter.is_step_frozen."""
|