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.
@@ -0,0 +1,62 @@
1
+ """Public API surface for pydantic-jsonpointer.
2
+
3
+ Importing this package auto-registers ``BaseModelAdapter`` against
4
+ ``pydantic.BaseModel`` so traversal of any BaseModel subclass works out of
5
+ the box without explicit setup.
6
+ """
7
+
8
+ from pydantic import BaseModel as _BaseModel
9
+
10
+ from ._model_path import pointer_from_model
11
+ from .adapters import ContainerAdapter, adapter_for, register
12
+ from .errors import (
13
+ AdapterNotFoundError,
14
+ ImmutableTargetError,
15
+ InvalidTokenError,
16
+ PointerError,
17
+ PointerNotFoundError,
18
+ RootRebindError,
19
+ )
20
+ from .pydantic_adapter import (
21
+ BaseModelAdapter,
22
+ ByAttribute,
23
+ BySerializationAlias,
24
+ ByValidationAlias,
25
+ FieldResolver,
26
+ )
27
+ from .traversal import (
28
+ Ptr,
29
+ add_value,
30
+ get_value,
31
+ remove_value,
32
+ resolve,
33
+ set_value,
34
+ )
35
+ from .types import JsonPointer
36
+
37
+ register(_BaseModel, BaseModelAdapter(), override=True)
38
+
39
+ __all__ = [
40
+ "JsonPointer",
41
+ "pointer_from_model",
42
+ "Ptr",
43
+ "resolve",
44
+ "get_value",
45
+ "set_value",
46
+ "add_value",
47
+ "remove_value",
48
+ "ContainerAdapter",
49
+ "register",
50
+ "adapter_for",
51
+ "FieldResolver",
52
+ "ByAttribute",
53
+ "BySerializationAlias",
54
+ "ByValidationAlias",
55
+ "BaseModelAdapter",
56
+ "PointerError",
57
+ "PointerNotFoundError",
58
+ "AdapterNotFoundError",
59
+ "RootRebindError",
60
+ "InvalidTokenError",
61
+ "ImmutableTargetError",
62
+ ]
@@ -0,0 +1 @@
1
+ VERSION = "0.1.0-beta.1"
@@ -0,0 +1,379 @@
1
+ from __future__ import annotations
2
+
3
+ import types as _stdlib_types
4
+ import typing
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload
7
+
8
+ from pydantic import BaseModel, RootModel
9
+ from typing_extensions import TypeVar as _TypeVarExt
10
+
11
+ from .errors import PointerError
12
+ from .pydantic_adapter import BySerializationAlias, FieldResolver
13
+
14
+ if TYPE_CHECKING:
15
+ from .types import JsonPointer
16
+
17
+ _T = TypeVar("_T", bound=BaseModel)
18
+ _P = _TypeVarExt("_P", default=Any)
19
+
20
+ _MAX_ADVANCE_DEPTH = 64
21
+
22
+
23
+ def _advance(
24
+ annotation: Any,
25
+ *,
26
+ for_index: bool = False,
27
+ index: int | None = None,
28
+ ) -> type[BaseModel] | None:
29
+ """Walk a type annotation extracting the BaseModel subclass for traversal.
30
+
31
+ Returns the BaseModel subclass that the next navigation step should resolve
32
+ against, or ``None`` when the annotation is a leaf type, an ambiguous
33
+ Union, a container (without ``for_index``), or any type lacking model
34
+ context.
35
+ """
36
+ for _ in range(_MAX_ADVANCE_DEPTH):
37
+ origin = typing.get_origin(annotation)
38
+
39
+ # PEP 695 type alias (Python 3.12+): ``type Foo = X`` produces a
40
+ # TypeAliasType whose get_origin() is None but whose __value__ holds
41
+ # the aliased type. Probe with getattr so this works on all supported
42
+ # Python versions and with typing_extensions.TypeAliasType too.
43
+ if origin is None:
44
+ _alias_val = getattr(annotation, "__value__", None)
45
+ if _alias_val is not None and _alias_val is not annotation:
46
+ annotation = _alias_val
47
+ continue
48
+
49
+ if origin is typing.Annotated:
50
+ args = typing.get_args(annotation)
51
+ if args:
52
+ annotation = args[0]
53
+ continue
54
+ return None
55
+
56
+ if origin is typing.Union or origin is _stdlib_types.UnionType:
57
+ args = typing.get_args(annotation)
58
+ non_none = [a for a in args if a is not type(None)]
59
+ if len(non_none) == 1:
60
+ annotation = non_none[0]
61
+ continue
62
+ return None
63
+
64
+ if isinstance(annotation, type) and issubclass(annotation, RootModel):
65
+ root_field = annotation.model_fields.get("root")
66
+ if root_field is not None and root_field.annotation is not None:
67
+ annotation = root_field.annotation
68
+ continue
69
+ return None
70
+
71
+ if for_index and origin in (list, tuple):
72
+ args = typing.get_args(annotation)
73
+ if args:
74
+ if origin is tuple and args[-1] is not ...:
75
+ # Fixed-length heterogeneous tuple: index determines which type.
76
+ if index is None or index < 0 or index >= len(args):
77
+ return None
78
+ annotation = args[index]
79
+ else:
80
+ # list or homogeneous tuple[T, ...]
81
+ if index is None:
82
+ # index=None is the "-" tail sentinel (RFC 6901 §4). "-" is
83
+ # only valid as a terminal add-position token; chaining further
84
+ # (.attr or [i]) produces a pointer that can never be resolved
85
+ # via get/set/remove. Lose model context for both list and tuple
86
+ # so any further chaining raises AttributeError at build time.
87
+ return None
88
+ annotation = args[0]
89
+ for_index = False
90
+ continue
91
+
92
+ if not for_index:
93
+ if (
94
+ origin is not None
95
+ and isinstance(origin, type)
96
+ and issubclass(origin, BaseModel)
97
+ ):
98
+ return origin
99
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
100
+ return annotation
101
+
102
+ return None
103
+ raise PointerError( # _advance depth exceeded
104
+ "annotation traversal depth exceeded; possible self-referential type"
105
+ )
106
+
107
+
108
+ def _advance_attr(annotation: Any) -> type[BaseModel] | None:
109
+ """Return the BaseModel subclass for the *next* ``.attr`` access."""
110
+ return _advance(annotation, for_index=False)
111
+
112
+
113
+ def _advance_index(
114
+ annotation: Any, *, index: int | None = None
115
+ ) -> type[BaseModel] | None:
116
+ """Return the BaseModel subclass for the *next* ``[index]`` access."""
117
+ return _advance(annotation, for_index=True, index=index)
118
+
119
+
120
+ def _peel_item_annotation(annotation: Any, *, index: int | None = None) -> Any:
121
+ """Return the raw item annotation from a container after peeling wrappers.
122
+
123
+ Unlike _advance_index, this does not require the item to be a BaseModel — it
124
+ stops as soon as it extracts the item type from a list or tuple. Used to carry
125
+ _pending_annotation forward across chained __getitem__ calls (e.g. grid[0][0]
126
+ on grid: list[list[Item]] needs list[Item] as pending context after the first [0]).
127
+ Returns None when annotation is not a recognizable container.
128
+ """
129
+ for _ in range(_MAX_ADVANCE_DEPTH):
130
+ origin = typing.get_origin(annotation)
131
+
132
+ if origin is None:
133
+ _alias_val = getattr(annotation, "__value__", None)
134
+ if _alias_val is not None and _alias_val is not annotation:
135
+ annotation = _alias_val
136
+ continue
137
+ # fall through: let the RootModel check below handle bare RootModel subclasses
138
+
139
+ if origin is typing.Annotated:
140
+ args = typing.get_args(annotation)
141
+ if args:
142
+ annotation = args[0]
143
+ continue
144
+ return None
145
+
146
+ if origin is typing.Union or origin is _stdlib_types.UnionType:
147
+ args = typing.get_args(annotation)
148
+ non_none = [a for a in args if a is not type(None)]
149
+ if len(non_none) == 1:
150
+ annotation = non_none[0]
151
+ continue
152
+ return None
153
+
154
+ if isinstance(annotation, type) and issubclass(annotation, RootModel):
155
+ root_field = annotation.model_fields.get("root")
156
+ if root_field is not None and root_field.annotation is not None:
157
+ annotation = root_field.annotation
158
+ continue
159
+ return None
160
+
161
+ if origin in (list, tuple):
162
+ args = typing.get_args(annotation)
163
+ if not args:
164
+ return None
165
+ if origin is tuple and args[-1] is not ...:
166
+ if index is None or index < 0 or index >= len(args):
167
+ return None
168
+ return args[index]
169
+ if origin is tuple and index is None:
170
+ return None
171
+ return args[0]
172
+
173
+ return None
174
+
175
+ raise PointerError( # _peel_item_annotation depth exceeded
176
+ "annotation traversal depth exceeded; possible self-referential type"
177
+ )
178
+
179
+
180
+ @overload
181
+ def pointer_from_model(
182
+ model: type[_T],
183
+ *,
184
+ resolver: FieldResolver | None = None,
185
+ ) -> _ModelPath[_T, Any]: ...
186
+
187
+
188
+ @overload
189
+ def pointer_from_model(
190
+ model: _T,
191
+ *,
192
+ resolver: FieldResolver | None = None,
193
+ ) -> _ModelPath[_T, Any]: ...
194
+
195
+
196
+ def pointer_from_model(
197
+ model: type[BaseModel] | BaseModel,
198
+ *,
199
+ resolver: FieldResolver | None = None,
200
+ ) -> _ModelPath[Any, Any]:
201
+ """Start building a ``JsonPointer`` from a pydantic model's attribute chain.
202
+
203
+ Accepts either a model *class* or an *instance*. Instance entry uses
204
+ only ``type(model)`` — no runtime instance peeking. For Union-typed
205
+ fields, narrow with ``isinstance`` and pass the narrowed value.
206
+
207
+ Usage::
208
+
209
+ ptr = pointer_from_model(User).name
210
+ ptr = pointer_from_model(User).address.city
211
+ ptr = pointer_from_model(Order).items[0].name
212
+ if isinstance(event.payload, JsonBody):
213
+ ptr = pointer_from_model(event.payload).body
214
+ """
215
+ if resolver is None:
216
+ resolver = BySerializationAlias()
217
+
218
+ if isinstance(model, BaseModel):
219
+ model_cls = type(model)
220
+ elif isinstance(model, type) and issubclass(model, BaseModel):
221
+ model_cls = model
222
+ else:
223
+ msg = (
224
+ f"pointer_from_model expects a BaseModel class or instance, "
225
+ f"got {type(model).__name__}"
226
+ )
227
+ raise TypeError(msg)
228
+
229
+ pending: Any = None
230
+ effective_model_cls = model_cls
231
+ if issubclass(model_cls, RootModel):
232
+ root_field = model_cls.model_fields.get("root")
233
+ if root_field is not None and root_field.annotation is not None:
234
+ pending = root_field.annotation
235
+ inner_cls = _advance_attr(pending)
236
+ if inner_cls is not None:
237
+ effective_model_cls = inner_cls
238
+
239
+ return _ModelPath(
240
+ _model_cls=effective_model_cls,
241
+ _resolver=resolver,
242
+ _pending_annotation=pending,
243
+ )
244
+
245
+
246
+ @dataclass(frozen=True, slots=True)
247
+ class _ModelPath(Generic[_T, _P]):
248
+ """Proxy that captures attribute chains on a pydantic model.
249
+
250
+ Produced by ``pointer_from_model()``. Each ``.attr`` access records the
251
+ attribute name (resolved to a token via a ``FieldResolver``) and may
252
+ advance the model class for deeper chaining. ``[index]`` inserts a raw
253
+ token and may advance the model to the container's item type.
254
+
255
+ Private — not exported. The public API is ``pointer_from_model()``.
256
+ """
257
+
258
+ _model_cls: type[_T]
259
+ _tokens: tuple[str, ...] = ()
260
+ _resolver: FieldResolver | None = None
261
+ _pending_annotation: _P = cast(_P, None)
262
+ _model_ctx_lost: bool = False
263
+
264
+ def __getattribute__(self, name: str) -> Any:
265
+ # Model fields take priority over class-defined methods/attributes so
266
+ # fields named e.g. 'build' are reachable via attribute chaining.
267
+ # Skip field routing when context is lost — the user is calling a class
268
+ # method (e.g. build()) to finalize, not navigating a field.
269
+ if not name.startswith("_"):
270
+ model_ctx_lost: bool = object.__getattribute__(self, "_model_ctx_lost")
271
+ if not model_ctx_lost:
272
+ model_cls: type[BaseModel] = object.__getattribute__(self, "_model_cls")
273
+ if name in model_cls.model_fields:
274
+ return _ModelPath.__getattr__(self, name)
275
+ return object.__getattribute__(self, name)
276
+
277
+ def build(self) -> JsonPointer:
278
+ """Resolve accumulated tokens into a ``JsonPointer``."""
279
+ from .types import JsonPointer
280
+
281
+ return JsonPointer.from_tokens(*self._tokens)
282
+
283
+ def __call__(self) -> JsonPointer:
284
+ """Finalize the chain and return a ``JsonPointer``.
285
+
286
+ Use this instead of ``.build()`` when the underlying model has a field
287
+ named ``build`` — in that case ``.build`` navigates to the field, and
288
+ ``()`` is the safe way to finalize without adding an extra token.
289
+ """
290
+ return _ModelPath.build(self)
291
+
292
+ def __str__(self) -> str:
293
+ return str(_ModelPath.build(self))
294
+
295
+ def __repr__(self) -> str:
296
+ return (
297
+ f"_ModelPath(model={self._model_cls.__name__!r}, tokens={self._tokens!r})"
298
+ )
299
+
300
+ def __getattr__(self, name: str) -> _ModelPath[Any, Any]:
301
+ if self._model_ctx_lost:
302
+ raise AttributeError(
303
+ f"cannot chain .{name}: model type context was lost "
304
+ "(leaf type, ambiguous Union, or non-list container); "
305
+ "narrow via isinstance() and pass the narrowed value to "
306
+ "pointer_from_model()"
307
+ )
308
+ if issubclass(self._model_cls, RootModel):
309
+ raise AttributeError(
310
+ f"cannot chain .{name} on {self._model_cls.__name__!r}: "
311
+ "RootModel subclasses are traversed transparently at runtime; "
312
+ "use [index] to navigate into the wrapped container instead"
313
+ )
314
+ field_info = self._model_cls.model_fields.get(name)
315
+ if field_info is None:
316
+ raise AttributeError(f"{self._model_cls.__name__!r} has no field {name!r}")
317
+ if self._resolver is None:
318
+ raise AttributeError(
319
+ "_ModelPath has no resolver; construct via pointer_from_model()"
320
+ )
321
+ token = self._resolver.to_token(self._model_cls, name)
322
+ annotation = field_info.annotation
323
+ next_cls = _advance_attr(annotation)
324
+ return _ModelPath(
325
+ _model_cls=next_cls or self._model_cls,
326
+ _tokens=self._tokens + (token,),
327
+ _resolver=self._resolver,
328
+ _pending_annotation=annotation,
329
+ _model_ctx_lost=next_cls is None,
330
+ )
331
+
332
+ def __getitem__(self, index: int | str) -> _ModelPath[Any, Any]:
333
+ if self._pending_annotation is None and not self._model_ctx_lost:
334
+ raise TypeError(
335
+ f"cannot index into {self._model_cls.__name__!r}: "
336
+ "navigate to a list or tuple field first"
337
+ )
338
+ if not isinstance(index, (int, str)):
339
+ raise TypeError(
340
+ f"list index must be int or str, got {type(index).__name__!r}"
341
+ )
342
+ if isinstance(index, bool) or (isinstance(index, int) and index < 0):
343
+ raise ValueError(
344
+ f"invalid list index {index!r} is not a valid RFC 6901 array token"
345
+ )
346
+ if isinstance(index, str) and index != "-":
347
+ _ascii_digits = bool(index) and all("0" <= c <= "9" for c in index)
348
+ if not _ascii_digits or (len(index) > 1 and index[0] == "0"):
349
+ raise ValueError(
350
+ f"invalid array token {index!r}: "
351
+ "must be a non-negative integer string or '-'"
352
+ )
353
+ token = str(index)
354
+ is_dash = isinstance(index, str) and index == "-"
355
+ int_index: int | None = None
356
+ if isinstance(index, int):
357
+ int_index = index
358
+ elif isinstance(index, str) and index != "-":
359
+ int_index = int(index)
360
+ next_cls = _advance_index(self._pending_annotation, index=int_index)
361
+ next_pending_annotation: Any = None
362
+ # "-" is a terminal add-position token: context loss must not be recovered
363
+ # by a subsequent [i] step. Keeping _pending_annotation=None prevents
364
+ # _advance_index from resolving a nested container's item type.
365
+ if next_cls is None and not is_dash:
366
+ next_pending_annotation = _peel_item_annotation(
367
+ self._pending_annotation, index=int_index
368
+ )
369
+ return _ModelPath(
370
+ _model_cls=next_cls or self._model_cls,
371
+ _tokens=self._tokens + (token,),
372
+ _resolver=self._resolver,
373
+ _pending_annotation=next_pending_annotation,
374
+ _model_ctx_lost=next_cls is None,
375
+ )
376
+
377
+ def __truediv__(self, token: str | int) -> JsonPointer:
378
+ """Append a raw token to the pointer (terminal — model-awareness ends)."""
379
+ return _ModelPath.build(self) / token