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,117 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import sys
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ if TYPE_CHECKING:
8
+ if sys.version_info >= (3, 11):
9
+ from typing import Self
10
+ else:
11
+ from typing_extensions import Self
12
+
13
+ from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
14
+ from pydantic.json_schema import JsonSchemaValue
15
+ from pydantic_core import CoreSchema, core_schema
16
+
17
+ _INVALID_TILDE_RE = re.compile(r"~(?![01])")
18
+
19
+
20
+ def _escape_token(token: str) -> str:
21
+ """Escape a reference token per RFC 6901 section 3."""
22
+ return token.replace("~", "~0").replace("/", "~1")
23
+
24
+
25
+ def _unescape_token(token: str) -> str:
26
+ """Unescape a reference token per RFC 6901 section 3."""
27
+ return token.replace("~1", "/").replace("~0", "~")
28
+
29
+
30
+ class JsonPointer(str):
31
+ """RFC 6901 JSON Pointer.
32
+
33
+ A JSON Pointer is either the empty string (referencing the whole document)
34
+ or a sequence of reference tokens each prefixed by ``/``.
35
+
36
+ Construct from a raw string, from individual tokens, or by chaining
37
+ the ``/`` operator::
38
+
39
+ ptr = JsonPointer("/foo/0")
40
+ ptr = JsonPointer.from_tokens("foo", 0)
41
+ ptr = JsonPointer() / "foo" / 0
42
+ """
43
+
44
+ __slots__ = ("_tokens",)
45
+ _tokens: tuple[str, ...]
46
+
47
+ def __new__(cls, value: str = "") -> Self:
48
+ if not isinstance(value, str):
49
+ msg = f"JsonPointer requires a str, got {type(value).__name__}"
50
+ raise TypeError(msg)
51
+ if value != "" and not value.startswith("/"):
52
+ msg = f"JSON Pointer must be empty or start with '/': {value!r}"
53
+ raise ValueError(msg)
54
+ if _INVALID_TILDE_RE.search(value):
55
+ msg = f"Invalid escape in JSON Pointer (~ must be followed by 0 or 1): {value!r}"
56
+ raise ValueError(msg)
57
+ tokens: tuple[str, ...] = (
58
+ ()
59
+ if value == ""
60
+ else tuple(_unescape_token(t) for t in value[1:].split("/"))
61
+ )
62
+ return cls.__with_tokens(value, tokens)
63
+
64
+ @classmethod
65
+ def __with_tokens(cls, value: str, tokens: tuple[str, ...]) -> Self:
66
+ instance = str.__new__(cls, value)
67
+ instance._tokens = tokens
68
+ return instance
69
+
70
+ @classmethod
71
+ def __get_pydantic_core_schema__(
72
+ cls,
73
+ _source_type: type[Any],
74
+ _handler: GetCoreSchemaHandler,
75
+ ) -> CoreSchema:
76
+ return core_schema.no_info_wrap_validator_function(
77
+ cls._pydantic_validate,
78
+ core_schema.str_schema(),
79
+ serialization=core_schema.to_string_ser_schema(),
80
+ )
81
+
82
+ @classmethod
83
+ def __get_pydantic_json_schema__(
84
+ cls,
85
+ _core_schema: CoreSchema,
86
+ handler: GetJsonSchemaHandler,
87
+ ) -> JsonSchemaValue:
88
+ return handler(core_schema.str_schema())
89
+
90
+ @classmethod
91
+ def _pydantic_validate(cls, value: Any, handler: Any) -> Self:
92
+ raw = handler(value)
93
+ return cls(raw)
94
+
95
+ @classmethod
96
+ def from_tokens(cls, *tokens: str | int) -> Self:
97
+ """Build a pointer from unescaped reference tokens.
98
+
99
+ Tokens are escaped per RFC 6901 (``~`` -> ``~0``, ``/`` -> ``~1``).
100
+ """
101
+ if not tokens:
102
+ return cls.__with_tokens("", ())
103
+ str_tokens = tuple(str(t) for t in tokens)
104
+ value = "/" + "/".join(_escape_token(t) for t in str_tokens)
105
+ return cls.__with_tokens(value, str_tokens)
106
+
107
+ def __truediv__(self, token: str | int) -> Self:
108
+ """Append a reference token: ``ptr / "key" / 0``."""
109
+ str_token = str(token)
110
+ new_value = str(self) + "/" + _escape_token(str_token)
111
+ new_tokens = self._tokens + (str_token,)
112
+ return type(self).__with_tokens(new_value, new_tokens)
113
+
114
+ @property
115
+ def tokens(self) -> tuple[str, ...]:
116
+ """Decompose into unescaped reference tokens."""
117
+ return self._tokens
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: pydantic-jsonpointer
3
+ Version: 0.1.0-beta.1
4
+ Summary: JSONPointer (RFC6901) implementation for Pydantic
5
+ Project-URL: Homepage, https://pydantic-jsonpointer.codemageddon.me/
6
+ Project-URL: Repository, https://github.com/kubex-py/pydantic-jsonpointer.git
7
+ Project-URL: Issues, https://github.com/kubex-py/pydantic-jsonpointer/issues
8
+ Project-URL: Changelog, https://github.com/kubex-py/pydantic-jsonpointer/blob/main/CHANGELOG.md
9
+ Project-URL: Documentation, https://pydantic-jsonpointer.codemageddon.me/
10
+ Author-email: Codemageddon <dev@codemageddon.me>
11
+ Maintainer-email: Codemageddon <dev@codemageddon.me>
12
+ License: MIT License
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Build Tools
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: pydantic<3,>=2.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ <p align="center">
28
+ <img src="docs/assets/logo.png" alt="pydantic-jsonpointer logo" width="180">
29
+ </p>
30
+
31
+ # `pydantic-jsonpointer`
32
+
33
+ **JSONPointer ([RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)) implementation for Pydantic 2.x.** A typed `JsonPointer` string for use in Pydantic models, plus a traversal API that walks `dict` / `list` / `tuple` / `pydantic.BaseModel` graphs through a pluggable adapter protocol. Supports read, set, add, and remove operations with alias-aware traversal and transitive freeze propagation.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install pydantic-jsonpointer
39
+ # or: uv add pydantic-jsonpointer / poetry add pydantic-jsonpointer / pdm add pydantic-jsonpointer
40
+ ```
41
+
42
+ ## Quick example
43
+
44
+ ```python
45
+ from pydantic import BaseModel, Field
46
+ from pydantic_jsonpointer import JsonPointer, resolve
47
+
48
+ class Item(BaseModel):
49
+ name: str = Field(serialization_alias="itemName")
50
+ qty: int
51
+
52
+ class Order(BaseModel):
53
+ items: list[Item]
54
+
55
+ order = Order(items=[Item(name="apple", qty=3)])
56
+ ptr = resolve(order, JsonPointer("/items/0/itemName"))
57
+ print(ptr.get()) # "apple"
58
+ ptr.set("banana")
59
+ print(order.items[0].name) # "banana"
60
+ ```
61
+
62
+ ### With plain dicts/lists (no pydantic needed)
63
+
64
+ ```python
65
+ from pydantic_jsonpointer import JsonPointer as P, get_value, set_value
66
+
67
+ doc = {"items": [{"name": "a"}, {"name": "b"}]}
68
+ get_value(doc, P("/items/1/name")) # "b"
69
+ set_value(doc, P("/items/0/name"), "x")
70
+ ```
71
+
72
+ ### Building pointers from models (reverse)
73
+
74
+ ```python
75
+ from pydantic import BaseModel
76
+ from pydantic_jsonpointer import pointer_from_model
77
+
78
+ class Address(BaseModel):
79
+ city: str
80
+
81
+ class User(BaseModel):
82
+ name: str
83
+ address: Address
84
+
85
+ ptr = pointer_from_model(User).address.city.build() # → JsonPointer("/address/city")
86
+ ```
87
+
88
+ Also supports `RootModel`, list indexing, Union narrowing, and swappable alias resolvers.
89
+
90
+ ### Mypy plugin (opt-in)
91
+
92
+ An opt-in mypy plugin validates `pointer_from_model` attribute chains at every depth, catching unknown field names and invalid array indices at type-check time:
93
+
94
+ ```toml
95
+ # pyproject.toml
96
+ [tool.mypy]
97
+ plugins = "pydantic_jsonpointer.mypy_plugin"
98
+ ```
99
+
100
+ With the plugin enabled, `pointer_from_model(User).typo` is a type error; invalid array indices like `-1` or `True` are caught statically; ambiguous `Union[ModelA, ModelB]` chains produce a hard error pointing to `isinstance` narrowing.
101
+
102
+ ## Documentation
103
+
104
+ Full documentation at [pydantic-jsonpointer.codemageddon.me](https://pydantic-jsonpointer.codemageddon.me/) — covers traversal, adapters, model-based pointers, and all public APIs.
@@ -0,0 +1,13 @@
1
+ pydantic_jsonpointer/__init__.py,sha256=M6wkaI0VF19oSkGvAbzYwA_HMnj7lioiX0JgA_zRZjQ,1370
2
+ pydantic_jsonpointer/__version__.py,sha256=QUazSeMTP1KvNEwGROwb6WKiE2WEMaWaV8fPst0Se6I,25
3
+ pydantic_jsonpointer/_model_path.py,sha256=XsFxC7YSoUVqeXw3JOVk83-wMK8YhbHqzvfqt_vxUEk,14879
4
+ pydantic_jsonpointer/adapters.py,sha256=bICP7EIKlAyZTPvuNrAUvt6mdL-rbHLtVxEaNa-i9nc,11782
5
+ pydantic_jsonpointer/errors.py,sha256=SDHcjoVzBYbZC3sYwu02oL7x94pkNsWn8CKueT2d4hs,1588
6
+ pydantic_jsonpointer/mypy_plugin.py,sha256=VrGkyvX1Jr0qShsu7OPaffQy4RRDAC497PsjE5L77vY,36347
7
+ pydantic_jsonpointer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pydantic_jsonpointer/pydantic_adapter.py,sha256=Qvkl5sLClP63lvZvE8qDz47FSYLw5Luqypl1dDBuhBE,13185
9
+ pydantic_jsonpointer/traversal.py,sha256=eYxn5V8AJHzOue0NlFkqd5MYOzNhamHQLBUXMauIBkI,12510
10
+ pydantic_jsonpointer/types.py,sha256=LZnaD6iIvOKHyOqyeGOdIy9TFv0hJ9uE5gU9Jz1xF2k,3826
11
+ pydantic_jsonpointer-0.1.0b1.dist-info/METADATA,sha256=kekI1zDEA_uADWPAJDvJfcA6Q8tz21Xi4HvqpQbu_-c,3798
12
+ pydantic_jsonpointer-0.1.0b1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ pydantic_jsonpointer-0.1.0b1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any