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.
File without changes
@@ -0,0 +1,333 @@
1
+ """Pydantic-specific traversal support.
2
+
3
+ Provides:
4
+ - FieldResolver Protocol: maps RFC 6901 tokens <-> Python attribute names
5
+ - Three shipped resolvers: ByAttribute, BySerializationAlias, ByValidationAlias
6
+ - BaseModelAdapter: ContainerAdapter for pydantic.BaseModel instances
7
+
8
+ ``BaseModelAdapter`` is auto-registered against ``pydantic.BaseModel`` in
9
+ ``pydantic_jsonpointer/__init__.py``; importing *this* module alone has no
10
+ side effects on the adapter registry.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import sys
17
+ import types
18
+ import typing
19
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
20
+
21
+ from pydantic import AliasChoices, AliasPath, BaseModel, RootModel
22
+
23
+ from .errors import InvalidTokenError, PointerNotFoundError
24
+
25
+ if TYPE_CHECKING:
26
+ if sys.version_info >= (3, 11):
27
+ from typing import Self
28
+ else:
29
+ from typing_extensions import Self
30
+
31
+
32
+ @runtime_checkable
33
+ class FieldResolver(Protocol):
34
+ """Maps RFC 6901 tokens to Python attribute names on a Pydantic model.
35
+
36
+ Implementations must be stateless and side-effect-free.
37
+ """
38
+
39
+ def to_attr(self, model_cls: type[BaseModel], token: str) -> str | None:
40
+ """Return the Python attribute name on `model_cls` that this token
41
+ addresses, or None if no field matches under this resolver's policy.
42
+ """
43
+ ...
44
+
45
+ def to_token(self, model_cls: type[BaseModel], attr: str) -> str:
46
+ """Inverse of `to_attr`: given an attribute name, return the token
47
+ that should appear in a pointer addressing that field under this
48
+ resolver's policy.
49
+ """
50
+ ...
51
+
52
+
53
+ class ByAttribute:
54
+ """Resolves tokens against Python attribute names only.
55
+
56
+ Strictest policy — no aliases are consulted. Useful when patches are
57
+ authored in code against models with attribute-name access patterns.
58
+ """
59
+
60
+ def to_attr(self, model_cls: type[BaseModel], token: str) -> str | None:
61
+ if token in model_cls.model_fields:
62
+ return token
63
+ return None
64
+
65
+ def to_token(self, model_cls: type[BaseModel], attr: str) -> str:
66
+ return attr
67
+
68
+
69
+ class BySerializationAlias:
70
+ """Resolves tokens against the name that appears in ``model_dump(by_alias=True)``.
71
+
72
+ Match priority for ``to_attr`` (and equivalent precedence for ``to_token``):
73
+ 1. ``field.serialization_alias``
74
+ 2. ``field.alias``
75
+ 3. attribute name (only if neither alias is set)
76
+
77
+ This is the default resolver because JSON-Patch documents typically
78
+ originate from the same serialized vocabulary the model emits.
79
+ """
80
+
81
+ def to_attr(self, model_cls: type[BaseModel], token: str) -> str | None:
82
+ for attr_name, field in model_cls.model_fields.items():
83
+ if field.serialization_alias is not None:
84
+ if token == field.serialization_alias:
85
+ return attr_name
86
+ continue
87
+ if field.alias is not None:
88
+ if token == field.alias:
89
+ return attr_name
90
+ continue
91
+ if token == attr_name:
92
+ return attr_name
93
+ return None
94
+
95
+ def to_token(self, model_cls: type[BaseModel], attr: str) -> str:
96
+ field = model_cls.model_fields[attr]
97
+ if field.serialization_alias is not None:
98
+ return str(field.serialization_alias)
99
+ if field.alias is not None:
100
+ return str(field.alias)
101
+ return attr
102
+
103
+
104
+ def _validation_alias_strings(field: Any) -> list[str]:
105
+ """Extract every string token usable to validate this field.
106
+
107
+ Handles plain string aliases, ``AliasChoices`` (each choice may itself be
108
+ a string or an ``AliasPath``), and a bare ``AliasPath`` (whose first path
109
+ component is the top-level key). Returns an empty list if no
110
+ ``validation_alias`` is set on the field.
111
+ """
112
+ va = field.validation_alias
113
+ if va is None:
114
+ return []
115
+ if isinstance(va, str):
116
+ return [va]
117
+ if isinstance(va, AliasPath):
118
+ first = va.path[0] if va.path else None
119
+ return [first] if isinstance(first, str) else []
120
+ if isinstance(va, AliasChoices):
121
+ out: list[str] = []
122
+ for choice in va.choices:
123
+ if isinstance(choice, str):
124
+ out.append(choice)
125
+ elif isinstance(choice, AliasPath):
126
+ first = choice.path[0] if choice.path else None
127
+ if isinstance(first, str):
128
+ out.append(first)
129
+ return out
130
+ return []
131
+
132
+
133
+ class ByValidationAlias:
134
+ """Resolves tokens against the names accepted by ``model_validate``.
135
+
136
+ Match priority for ``to_attr``:
137
+ 1. any string in ``field.validation_alias`` (handling
138
+ ``AliasChoices``/``AliasPath``)
139
+ 2. ``field.alias``
140
+ 3. attribute name (only if neither ``validation_alias`` nor ``alias``
141
+ is set)
142
+ """
143
+
144
+ def to_attr(self, model_cls: type[BaseModel], token: str) -> str | None:
145
+ for attr_name, field in model_cls.model_fields.items():
146
+ va_strings = _validation_alias_strings(field)
147
+ if va_strings:
148
+ if token in va_strings:
149
+ return attr_name
150
+ continue
151
+ if field.alias is not None:
152
+ if token == field.alias:
153
+ return attr_name
154
+ continue
155
+ if token == attr_name:
156
+ return attr_name
157
+ return None
158
+
159
+ def to_token(self, model_cls: type[BaseModel], attr: str) -> str:
160
+ field = model_cls.model_fields[attr]
161
+ va_strings = _validation_alias_strings(field)
162
+ if va_strings:
163
+ return va_strings[0]
164
+ if field.alias is not None:
165
+ return str(field.alias)
166
+ return attr
167
+
168
+
169
+ _MAX_ALIAS_UNWRAP_DEPTH = 16
170
+
171
+
172
+ def _annotation_accepts_none(model_cls: type[BaseModel], attr: str) -> bool:
173
+ """True if the field's annotation includes ``None``.
174
+
175
+ Covers ``Optional[X]`` / ``Union[X, None]``, PEP 604 ``X | None`` (the two
176
+ distinct ``Union`` origins), the degenerate ``annotation is type(None)``
177
+ case, and PEP 695 ``type`` aliases (``TypeAliasType``) whose underlying
178
+ ``__value__`` resolves to one of the above. Aliases are unwrapped in a
179
+ bounded loop so a pathological self-referential alias cannot wedge here.
180
+ """
181
+ annotation = model_cls.model_fields[attr].annotation
182
+ for _ in range(_MAX_ALIAS_UNWRAP_DEPTH):
183
+ if annotation is None:
184
+ return False
185
+ origin = typing.get_origin(annotation)
186
+ if origin is typing.Union or origin is types.UnionType:
187
+ return type(None) in typing.get_args(annotation)
188
+ if annotation is type(None):
189
+ return True
190
+ # PEP 695 ``type Foo = X`` produces a ``TypeAliasType`` whose
191
+ # ``get_origin`` is ``None`` but whose ``__value__`` is the aliased
192
+ # annotation. Unwrap and retry.
193
+ inner = getattr(annotation, "__value__", None)
194
+ if inner is None or inner is annotation:
195
+ return False
196
+ annotation = inner
197
+ return False
198
+
199
+
200
+ class BaseModelAdapter:
201
+ """ContainerAdapter for ``pydantic.BaseModel`` instances.
202
+
203
+ Resolves tokens via a configurable ``FieldResolver`` (default
204
+ ``BySerializationAlias``). ``RootModel`` containers are transparently
205
+ unwrapped to their ``.root`` value via ``unwrap``.
206
+
207
+ Notes on semantics:
208
+ - ``set`` and ``add`` are equivalent: a BaseModel's field set is fixed,
209
+ so "create-or-replace" collapses to "replace".
210
+ - ``remove`` sets the field to ``None`` and returns the previous value;
211
+ only permitted when the field annotation accepts ``None``.
212
+ - ``is_step_frozen`` reports True when the parent model has
213
+ ``ConfigDict(frozen=True)`` or the addressed field has
214
+ ``Field(frozen=True)``; the walker propagates this taint to every
215
+ descendant slot.
216
+ """
217
+
218
+ def __init__(self, resolver: FieldResolver | None = None) -> None:
219
+ self._resolver: FieldResolver = resolver or BySerializationAlias()
220
+
221
+ def with_resolver(self, resolver: FieldResolver) -> Self:
222
+ """Return a copy of this adapter with ``resolver`` substituted.
223
+
224
+ Used by ``adapter_for(..., resolver=...)`` to apply a per-call
225
+ resolver override without mutating the registered adapter. Subclasses
226
+ that carry extra state inherit this behavior automatically because
227
+ ``copy.copy`` preserves it; subclasses whose extra state needs custom
228
+ cloning should override this method.
229
+ """
230
+ new = copy.copy(self)
231
+ new._resolver = resolver
232
+ return new
233
+
234
+ def resolve_token(self, parent: BaseModel, raw_token: str) -> str:
235
+ attr = self._resolver.to_attr(type(parent), raw_token)
236
+ if attr is None:
237
+ raise InvalidTokenError(
238
+ f"no field on {type(parent).__name__!r} matches token "
239
+ f"{raw_token!r} under resolver {type(self._resolver).__name__}"
240
+ )
241
+ return attr
242
+
243
+ def has(self, parent: BaseModel, key: int | str) -> bool:
244
+ if key not in type(parent).model_fields:
245
+ return False
246
+ # ``model_construct()`` may produce instances where a declared field
247
+ # was never set on the instance dict; in that case ``getattr`` would
248
+ # raise ``AttributeError``. Surface this as "no value present" so
249
+ # ``has`` and ``get`` agree.
250
+ return hasattr(parent, str(key))
251
+
252
+ def get(self, parent: BaseModel, key: int | str) -> Any:
253
+ model_cls = type(parent)
254
+ if key not in model_cls.model_fields:
255
+ raise PointerNotFoundError(f"{model_cls.__name__} has no field {key!r}")
256
+ try:
257
+ return getattr(parent, str(key))
258
+ except AttributeError as exc:
259
+ raise PointerNotFoundError(
260
+ f"{model_cls.__name__} field {str(key)!r} is not set on "
261
+ "this instance (declared but missing value)"
262
+ ) from exc
263
+
264
+ def set(self, parent: BaseModel, key: int | str, value: Any) -> None:
265
+ model_cls = type(parent)
266
+ if key not in model_cls.model_fields:
267
+ raise PointerNotFoundError(f"{model_cls.__name__} has no field {key!r}")
268
+ # Mirror ``has``: ``model_construct()`` can leave a declared field
269
+ # without a value on the instance. JSON-Patch ``replace`` requires the
270
+ # slot to already exist, so refuse rather than silently materializing
271
+ # the field. ``add`` retains the create-or-replace semantics below.
272
+ if not hasattr(parent, str(key)):
273
+ raise PointerNotFoundError(
274
+ f"{model_cls.__name__} field {str(key)!r} is not set on "
275
+ "this instance (declared but missing value)"
276
+ )
277
+ setattr(parent, str(key), value)
278
+
279
+ def add(self, parent: BaseModel, key: int | str, value: Any) -> None:
280
+ # ``add`` is create-or-replace: the field must be declared on the
281
+ # model (the schema is fixed), but unlike ``set`` it may materialize a
282
+ # field that ``model_construct()`` left unset on the instance.
283
+ model_cls = type(parent)
284
+ if key not in model_cls.model_fields:
285
+ raise PointerNotFoundError(f"{model_cls.__name__} has no field {key!r}")
286
+ setattr(parent, str(key), value)
287
+
288
+ def remove(self, parent: BaseModel, key: int | str) -> Any:
289
+ model_cls = type(parent)
290
+ if key not in model_cls.model_fields:
291
+ raise PointerNotFoundError(f"{model_cls.__name__} has no field {key!r}")
292
+ if not _annotation_accepts_none(model_cls, str(key)):
293
+ raise InvalidTokenError(
294
+ f"cannot remove non-Optional field "
295
+ f"{model_cls.__name__}.{str(key)!r}; field annotation does "
296
+ "not include None"
297
+ )
298
+ try:
299
+ captured = getattr(parent, str(key))
300
+ except AttributeError as exc:
301
+ raise PointerNotFoundError(
302
+ f"{model_cls.__name__} field {str(key)!r} is not set on "
303
+ "this instance (declared but missing value)"
304
+ ) from exc
305
+ setattr(parent, str(key), None)
306
+ return captured
307
+
308
+ def unwrap(self, value: Any) -> Any:
309
+ if isinstance(value, RootModel):
310
+ return value.root
311
+ return ...
312
+
313
+ def is_step_frozen(self, parent: BaseModel, key: int | str) -> bool:
314
+ if self.is_value_frozen(parent):
315
+ return True
316
+ field = type(parent).model_fields.get(str(key))
317
+ if field is None:
318
+ return False
319
+ return bool(field.frozen)
320
+
321
+ def is_value_frozen(self, value: BaseModel) -> bool:
322
+ model_cls = type(value)
323
+ if model_cls.model_config.get("frozen"):
324
+ return True
325
+ # For ``RootModel``, ``root`` is the sole field and the walker unwraps
326
+ # straight through it — there is no descent step at which the field's
327
+ # frozen flag could be observed. Surface it here so the unwrap chain
328
+ # propagates the taint to descendants.
329
+ if isinstance(value, RootModel):
330
+ root_field = model_cls.model_fields.get("root")
331
+ if root_field is not None and root_field.frozen:
332
+ return True
333
+ return False
@@ -0,0 +1,345 @@
1
+ """Pointer-traversal API: Ptr cursor, walker, and convenience functions.
2
+
3
+ Layered above `adapters` and `errors`. The Pydantic-specific
4
+ `BaseModelAdapter` is registered against `pydantic.BaseModel` in
5
+ `__init__.py`, so this module does not import Pydantic directly.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterator
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from .adapters import ContainerAdapter, adapter_for
15
+ from .errors import (
16
+ AdapterNotFoundError,
17
+ ImmutableTargetError,
18
+ PointerError,
19
+ PointerNotFoundError,
20
+ RootRebindError,
21
+ )
22
+ from .types import JsonPointer
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class Ptr:
27
+ """A live cursor into a ``(parent, key)`` slot of a document.
28
+
29
+ ``Ptr`` instances are produced by ``resolve(doc, pointer)``. Reads and
30
+ mutations always re-execute through ``_adapter``; the cursor does not
31
+ cache the value at ``(_parent, _key)``.
32
+ """
33
+
34
+ pointer: JsonPointer
35
+ _parent: Any
36
+ _key: int | str | None
37
+ _adapter: ContainerAdapter
38
+ _frozen: bool = False
39
+
40
+ @property
41
+ def parent(self) -> Any:
42
+ return self._parent
43
+
44
+ @property
45
+ def key(self) -> int | str | None:
46
+ return self._key
47
+
48
+ @property
49
+ def is_root(self) -> bool:
50
+ return self._key is None
51
+
52
+ @property
53
+ def is_frozen(self) -> bool:
54
+ return self._frozen
55
+
56
+ def get(self) -> Any:
57
+ """Return the value at this slot.
58
+
59
+ For the root Ptr returns the document itself. For non-root Ptrs
60
+ re-fetches through the adapter and raises ``PointerNotFoundError``
61
+ when the slot does not exist.
62
+ """
63
+ if self._key is None:
64
+ return self._parent
65
+ return self._adapter.get(self._parent, self._key)
66
+
67
+ def try_get(self, default: Any = ...) -> Any:
68
+ """Return the value at this slot, or ``default`` if missing.
69
+
70
+ With no ``default`` (or ``default=...``), behaves like ``get()`` —
71
+ raises ``PointerNotFoundError`` on missing. The ``Ellipsis`` singleton
72
+ serves as the "no default supplied" sentinel.
73
+ """
74
+ if self.exists():
75
+ return self.get()
76
+ if default is ...:
77
+ raise PointerNotFoundError(str(self.pointer))
78
+ return default
79
+
80
+ def exists(self) -> bool:
81
+ """True for the root Ptr, otherwise ``_adapter.has(_parent, _key)``."""
82
+ if self._key is None:
83
+ return True
84
+ return self._adapter.has(self._parent, self._key)
85
+
86
+ def set(self, value: Any) -> None:
87
+ """Replace the value at this slot. Target must already exist.
88
+
89
+ Raises ``RootRebindError`` on the root Ptr, ``ImmutableTargetError``
90
+ if any ancestor binding was frozen, ``PointerNotFoundError`` if the
91
+ slot does not exist.
92
+ """
93
+ self._guard_mutation()
94
+ assert self._key is not None
95
+ self._adapter.set(self._parent, self._key, value)
96
+
97
+ def add(self, value: Any) -> None:
98
+ """Insert (lists) or set (dicts/models) at this slot.
99
+
100
+ For dicts/models this creates-or-replaces; for lists this inserts at
101
+ the resolved index, with the ``"-"`` marker appending at the tail.
102
+ Raises ``RootRebindError`` on the root Ptr or ``ImmutableTargetError``
103
+ if any ancestor binding was frozen.
104
+ """
105
+ self._guard_mutation()
106
+ assert self._key is not None
107
+ self._adapter.add(self._parent, self._key, value)
108
+
109
+ def remove(self) -> Any:
110
+ """Remove and return the value at this slot.
111
+
112
+ Raises ``RootRebindError`` on the root Ptr, ``ImmutableTargetError``
113
+ if any ancestor binding was frozen, ``PointerNotFoundError`` if the
114
+ slot does not exist.
115
+ """
116
+ self._guard_mutation()
117
+ assert self._key is not None
118
+ return self._adapter.remove(self._parent, self._key)
119
+
120
+ def _guard_mutation(self) -> None:
121
+ if self._key is None:
122
+ raise RootRebindError(
123
+ "cannot mutate the root pointer; callers must rebind the "
124
+ "document variable themselves"
125
+ )
126
+ if self._frozen:
127
+ raise ImmutableTargetError(
128
+ f"target at {self.pointer!s} is under a frozen binding"
129
+ )
130
+
131
+
132
+ _MAX_UNWRAP_DEPTH = 64
133
+
134
+
135
+ def _prefix_adapter_not_found(
136
+ exc: AdapterNotFoundError, prefix: JsonPointer
137
+ ) -> AdapterNotFoundError:
138
+ """Re-wrap ``exc`` with the pointer prefix that reached the un-adaptable value.
139
+
140
+ ``str(exc)`` is used instead of ``exc.args[0]`` so the rewrap is safe even
141
+ if a caller raised ``AdapterNotFoundError`` with no args (degenerate case
142
+ that the library itself never produces, but third-party code could).
143
+ """
144
+ return AdapterNotFoundError(f"{exc} at pointer {str(prefix)!r}")
145
+
146
+
147
+ class _RootSentinelAdapter:
148
+ """No-op adapter for root Ptrs whose document has no registered adapter.
149
+
150
+ A root Ptr never invokes its adapter — ``Ptr.get``/``exists`` short-circuit
151
+ on ``_key is None`` and mutations raise ``RootRebindError`` before reaching
152
+ the adapter. This sentinel exists only to satisfy ``Ptr._adapter``'s shape
153
+ when ``resolve(doc, JsonPointer(""))`` is called with an un-adaptable
154
+ ``doc`` (e.g. a scalar). Every method raises if reached.
155
+ """
156
+
157
+ @staticmethod
158
+ def _unreachable() -> Any:
159
+ raise AssertionError("internal: root sentinel adapter must not be invoked")
160
+
161
+ def resolve_token(self, parent: Any, raw_token: str) -> int | str:
162
+ return self._unreachable() # type: ignore[no-any-return]
163
+
164
+ def has(self, parent: Any, key: int | str) -> bool:
165
+ return self._unreachable() # type: ignore[no-any-return]
166
+
167
+ def get(self, parent: Any, key: int | str) -> Any:
168
+ return self._unreachable()
169
+
170
+ def set(self, parent: Any, key: int | str, value: Any) -> None:
171
+ self._unreachable()
172
+
173
+ def add(self, parent: Any, key: int | str, value: Any) -> None:
174
+ self._unreachable()
175
+
176
+ def remove(self, parent: Any, key: int | str) -> Any:
177
+ return self._unreachable()
178
+
179
+ def unwrap(self, value: Any) -> Any:
180
+ return ...
181
+
182
+ def is_step_frozen(self, parent: Any, key: int | str) -> bool:
183
+ return False
184
+
185
+
186
+ _ROOT_SENTINEL_ADAPTER: ContainerAdapter = _RootSentinelAdapter()
187
+
188
+
189
+ def _unwrap_to_fixed_point(value: Any, *, resolver: Any = None) -> tuple[Any, bool]:
190
+ """Repeatedly apply the current adapter's ``unwrap`` until it returns ``...``.
191
+
192
+ Lets transparent wrappers (e.g. ``RootModel``) be invisible to the walker.
193
+ If no adapter is registered for ``value``'s type, the value is returned
194
+ unchanged so the walker can raise ``AdapterNotFoundError`` at the next
195
+ step with the original (non-unwrapped) value in context. The ``resolver``
196
+ kwarg is threaded into ``adapter_for`` so per-call Pydantic resolvers
197
+ apply during unwrapping too.
198
+
199
+ Returns ``(value, frozen)``: the freeze taint accumulates across the chain
200
+ so a frozen wrapper (e.g. a ``RootModel`` with ``ConfigDict(frozen=True)``)
201
+ propagates immutability to its unwrapped payload — descents into the inner
202
+ container inherit the taint and refuse writes.
203
+
204
+ A depth cap (``_MAX_UNWRAP_DEPTH``) bounds the loop so a misbehaving
205
+ third-party adapter that never returns ``...`` cannot wedge traversal
206
+ into an unkillable busy-loop.
207
+ """
208
+ frozen = False
209
+ for _ in range(_MAX_UNWRAP_DEPTH):
210
+ try:
211
+ adapter = adapter_for(value, resolver=resolver)
212
+ except AdapterNotFoundError:
213
+ return value, frozen
214
+ # ``is_value_frozen`` is an opt-in hook (matches ``is_step_frozen``'s
215
+ # role as a taint source). Adapters predating the hook — or those that
216
+ # simply don't care about whole-value immutability — may omit it and
217
+ # are treated as if it returned False, mirroring the built-in
218
+ # ``DictAdapter``/``ListAdapter`` behavior.
219
+ is_value_frozen = getattr(adapter, "is_value_frozen", None)
220
+ if is_value_frozen is not None and is_value_frozen(value):
221
+ frozen = True
222
+ unwrapped = adapter.unwrap(value)
223
+ if unwrapped is ...:
224
+ return value, frozen
225
+ value = unwrapped
226
+ raise PointerError(
227
+ f"unwrap chain exceeded {_MAX_UNWRAP_DEPTH} levels; a registered "
228
+ "adapter's unwrap() likely never returns ... (Ellipsis)"
229
+ )
230
+
231
+
232
+ def _iter_resolve(
233
+ doc: Any,
234
+ pointer: JsonPointer,
235
+ *,
236
+ resolver: Any = None,
237
+ ) -> Iterator[Ptr]:
238
+ """Yield Ptrs along ``pointer`` against ``doc``.
239
+
240
+ The sequence is: the root Ptr first, then one Ptr per token. For every
241
+ non-final token the value at ``(parent, key)`` is fetched and unwrapped
242
+ so the next iteration descends into the child container. The final Ptr
243
+ is yielded without fetching, so it may refer to a non-existent slot
244
+ (JSON-Patch ``add`` semantics, including the ``"-"`` array tail).
245
+
246
+ Private: not re-exported. Iteration shape may evolve; public callers go
247
+ through ``resolve`` or the convenience helpers.
248
+
249
+ The root Ptr is yielded with ``_parent=doc`` (the original document)
250
+ so ``get()`` returns exactly what the caller passed in, as the spec
251
+ mandates for the empty pointer. The unwrapped value is used only for
252
+ descent into child slots.
253
+
254
+ ``AdapterNotFoundError`` raised by ``adapter_for`` is re-thrown with the
255
+ pointer prefix that reached the un-adaptable value, per the spec edge-case
256
+ matrix.
257
+ """
258
+ descent_value, frozen = _unwrap_to_fixed_point(doc, resolver=resolver)
259
+ tokens = pointer.tokens
260
+
261
+ root_adapter: ContainerAdapter
262
+ try:
263
+ root_adapter = adapter_for(descent_value, resolver=resolver)
264
+ except AdapterNotFoundError as exc:
265
+ if tokens:
266
+ raise _prefix_adapter_not_found(exc, JsonPointer("")) from exc
267
+ root_adapter = _ROOT_SENTINEL_ADAPTER
268
+
269
+ yield Ptr(
270
+ pointer=JsonPointer(""),
271
+ _parent=doc,
272
+ _key=None,
273
+ _adapter=root_adapter,
274
+ _frozen=False,
275
+ )
276
+
277
+ value = descent_value
278
+ last_index = len(tokens) - 1
279
+
280
+ for i, token in enumerate(tokens):
281
+ try:
282
+ adapter = adapter_for(value, resolver=resolver)
283
+ except AdapterNotFoundError as exc:
284
+ prefix = JsonPointer.from_tokens(*tokens[:i])
285
+ raise _prefix_adapter_not_found(exc, prefix) from exc
286
+ key = adapter.resolve_token(value, token)
287
+ step_frozen = frozen or adapter.is_step_frozen(value, key)
288
+
289
+ partial_pointer = JsonPointer.from_tokens(*tokens[: i + 1])
290
+ ptr = Ptr(
291
+ pointer=partial_pointer,
292
+ _parent=value,
293
+ _key=key,
294
+ _adapter=adapter,
295
+ _frozen=step_frozen,
296
+ )
297
+
298
+ if i != last_index:
299
+ value, unwrap_frozen = _unwrap_to_fixed_point(
300
+ adapter.get(value, key), resolver=resolver
301
+ )
302
+ frozen = step_frozen or unwrap_frozen
303
+
304
+ yield ptr
305
+
306
+
307
+ def resolve(doc: Any, pointer: JsonPointer, *, resolver: Any = None) -> Ptr:
308
+ """Resolve ``pointer`` against ``doc`` and return a Ptr to the target slot.
309
+
310
+ The returned Ptr may have ``exists() == False`` (for JSON-Patch ``add`` on
311
+ a missing key, or for the array-tail ``"-"`` marker). For the empty
312
+ pointer the root Ptr is returned. The optional ``resolver`` kwarg
313
+ overrides the default ``BaseModelAdapter`` field-name policy for this
314
+ call only (no registry mutation).
315
+ """
316
+ last: Ptr | None = None
317
+ for ptr in _iter_resolve(doc, pointer, resolver=resolver):
318
+ last = ptr
319
+ if last is None:
320
+ raise PointerError("internal: _iter_resolve yielded no Ptr")
321
+ return last
322
+
323
+
324
+ def get_value(doc: Any, pointer: JsonPointer, *, resolver: Any = None) -> Any:
325
+ """Return the value at ``pointer`` in ``doc``."""
326
+ return resolve(doc, pointer, resolver=resolver).get()
327
+
328
+
329
+ def set_value(
330
+ doc: Any, pointer: JsonPointer, value: Any, *, resolver: Any = None
331
+ ) -> None:
332
+ """Replace the value at ``pointer`` in ``doc``. Target must already exist."""
333
+ resolve(doc, pointer, resolver=resolver).set(value)
334
+
335
+
336
+ def add_value(
337
+ doc: Any, pointer: JsonPointer, value: Any, *, resolver: Any = None
338
+ ) -> None:
339
+ """Insert (lists) or set (dicts/models) ``value`` at ``pointer`` in ``doc``."""
340
+ resolve(doc, pointer, resolver=resolver).add(value)
341
+
342
+
343
+ def remove_value(doc: Any, pointer: JsonPointer, *, resolver: Any = None) -> Any:
344
+ """Remove and return the value at ``pointer`` in ``doc``."""
345
+ return resolve(doc, pointer, resolver=resolver).remove()