jsonpatch 1.40__tar.gz → 1.42__tar.gz

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.
Files changed (30) hide show
  1. {jsonpatch-1.40 → jsonpatch-1.42}/MANIFEST.in +1 -0
  2. {jsonpatch-1.40/jsonpatch.egg-info → jsonpatch-1.42}/PKG-INFO +17 -2
  3. {jsonpatch-1.40 → jsonpatch-1.42}/README.md +14 -0
  4. {jsonpatch-1.40 → jsonpatch-1.42}/doc/tutorial.rst +108 -2
  5. jsonpatch-1.42/jsonpatch-stubs/__init__.pyi +148 -0
  6. {jsonpatch-1.40 → jsonpatch-1.42/jsonpatch.egg-info}/PKG-INFO +17 -2
  7. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch.egg-info/SOURCES.txt +3 -1
  8. jsonpatch-1.42/jsonpatch.egg-info/requires.txt +1 -0
  9. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch.egg-info/top_level.txt +1 -0
  10. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch.py +300 -28
  11. {jsonpatch-1.40 → jsonpatch-1.42}/property_tests.py +100 -0
  12. {jsonpatch-1.40 → jsonpatch-1.42}/pyproject.toml +3 -0
  13. jsonpatch-1.42/requirements.txt +1 -0
  14. {jsonpatch-1.40 → jsonpatch-1.42}/setup.py +5 -1
  15. {jsonpatch-1.40 → jsonpatch-1.42}/tests.py +569 -1
  16. jsonpatch-1.42/typetests/usage.py +111 -0
  17. jsonpatch-1.40/jsonpatch.egg-info/requires.txt +0 -1
  18. jsonpatch-1.40/requirements.txt +0 -1
  19. {jsonpatch-1.40 → jsonpatch-1.42}/AUTHORS +0 -0
  20. {jsonpatch-1.40 → jsonpatch-1.42}/LICENSE +0 -0
  21. {jsonpatch-1.40 → jsonpatch-1.42}/doc/commandline.rst +0 -0
  22. {jsonpatch-1.40 → jsonpatch-1.42}/doc/index.rst +0 -0
  23. {jsonpatch-1.40 → jsonpatch-1.42}/doc/mod-jsonpatch.rst +0 -0
  24. {jsonpatch-1.40 → jsonpatch-1.42}/ext_tests.py +0 -0
  25. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch.egg-info/dependency_links.txt +0 -0
  26. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch.egg-info/entry_points.txt +0 -0
  27. {jsonpatch-1.40 → jsonpatch-1.42}/jsonpatch_cli.py +0 -0
  28. {jsonpatch-1.40 → jsonpatch-1.42}/pytest.ini +0 -0
  29. {jsonpatch-1.40 → jsonpatch-1.42}/setup.cfg +0 -0
  30. {jsonpatch-1.40 → jsonpatch-1.42}/tests.js +0 -0
@@ -6,5 +6,6 @@ include doc/*.rst
6
6
  include property_tests.py
7
7
  include pytest.ini
8
8
  include ext_tests.py
9
+ include typetests/usage.py
9
10
  include AUTHORS
10
11
  include tests.js
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpatch
3
- Version: 1.40
3
+ Version: 1.42
4
4
  Summary: Apply JSON-Patches (RFC 6902)
5
5
  Home-page: https://github.com/stefankoegl/python-json-patch
6
6
  Author: Stefan Kögl
@@ -28,11 +28,12 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
28
28
  Classifier: Programming Language :: Python :: Implementation :: PyPy
29
29
  Classifier: Topic :: Software Development :: Libraries
30
30
  Classifier: Topic :: Utilities
31
+ Classifier: Typing :: Typed
31
32
  Requires-Python: >=3.10
32
33
  Description-Content-Type: text/markdown
33
34
  License-File: LICENSE
34
35
  License-File: AUTHORS
35
- Requires-Dist: jsonpointer>=3.2
36
+ Requires-Dist: jsonpointer>=3.8
36
37
  Dynamic: author
37
38
  Dynamic: author-email
38
39
  Dynamic: classifier
@@ -69,6 +70,20 @@ See source code for examples
69
70
  * CI: https://github.com/stefankoegl/python-json-patch/actions
70
71
  * Coveralls: https://coveralls.io/github/stefankoegl/python-json-patch
71
72
 
73
+ Type hints
74
+ ----------
75
+ jsonpatch ships type stubs (in the `jsonpatch-stubs` directory, as
76
+ jsonpatch.py is a single-file module), so type checkers such as mypy and
77
+ pyright work with it without further setup. JSON documents are typed as `Any`.
78
+
79
+ When changing the public API of jsonpatch.py, update
80
+ `jsonpatch-stubs/__init__.pyi` as well. These check that both agree, and that
81
+ typical usage in `typetests/usage.py` type-checks:
82
+
83
+ pip install mypy .
84
+ python -m mypy.stubtest --mypy-config-file pyproject.toml jsonpatch
85
+ cd typetests && mypy --config-file ../pyproject.toml usage.py
86
+
72
87
  Running external tests
73
88
  ----------------------
74
89
  To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_tests.py
@@ -21,6 +21,20 @@ See source code for examples
21
21
  * CI: https://github.com/stefankoegl/python-json-patch/actions
22
22
  * Coveralls: https://coveralls.io/github/stefankoegl/python-json-patch
23
23
 
24
+ Type hints
25
+ ----------
26
+ jsonpatch ships type stubs (in the `jsonpatch-stubs` directory, as
27
+ jsonpatch.py is a single-file module), so type checkers such as mypy and
28
+ pyright work with it without further setup. JSON documents are typed as `Any`.
29
+
30
+ When changing the public API of jsonpatch.py, update
31
+ `jsonpatch-stubs/__init__.pyi` as well. These check that both agree, and that
32
+ typical usage in `typetests/usage.py` type-checks:
33
+
34
+ pip install mypy .
35
+ python -m mypy.stubtest --mypy-config-file pyproject.toml jsonpatch
36
+ cd typetests && mypy --config-file ../pyproject.toml usage.py
37
+
24
38
  Running external tests
25
39
  ----------------------
26
40
  To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_tests.py
@@ -70,14 +70,16 @@ The operations of a patch refer to locations in the object it is applied to.
70
70
  A patch created with ``make_patch(src, dst)`` or ``JsonPatch.from_diff(src,
71
71
  dst)`` must therefore be applied to ``src`` (or to an object equal to it).
72
72
  Applying it to any other object, such as ``dst``, usually fails with a
73
- ``JsonPatchConflict``, because the locations it refers to don't exist there:
73
+ ``JsonPatchConflict``, because the locations it refers to don't exist there.
74
+ Here it is a ``JsonPatchPathNotFound``, the subclass of ``JsonPatchConflict``
75
+ that is raised when the location an operation acts on doesn't exist:
74
76
 
75
77
  .. code-block:: python
76
78
 
77
79
  >>> patch.apply(dst)
78
80
  Traceback (most recent call last):
79
81
  ...
80
- jsonpatch.JsonPatchConflict: can't remove a non-existent object 'foo'
82
+ jsonpatch.JsonPatchPathNotFound: can't remove a non-existent object 'foo'
81
83
 
82
84
  Applying it to an object with the same structure but different values may
83
85
  succeed, though, and overwrite those values. With ``generate_test_ops=True``
@@ -151,6 +153,110 @@ do not roll back changes already made in place:
151
153
  >>> original
152
154
  {'value': 2}
153
155
 
156
+ To get all-or-nothing behaviour without copying the document, pass
157
+ ``atomic=True`` together with ``in_place=True``. If an operation fails, the
158
+ changes of the preceding operations are undone before the exception is
159
+ raised, so the document is either fully patched or left unchanged:
160
+
161
+ .. code-block:: python
162
+
163
+ >>> original = {'value': 1}
164
+ >>> try:
165
+ ... jsonpatch.apply_patch(original, patch, in_place=True, atomic=True)
166
+ ... except jsonpatch.JsonPatchTestFailed:
167
+ ... print('Test failed')
168
+ Test failed
169
+ >>> original
170
+ {'value': 1}
171
+
172
+ This only keeps the values that the patch removes or replaces until it has
173
+ been applied, so it needs much less memory than ``in_place=False`` for large
174
+ documents. The original containers are restored, so references into the
175
+ document stay valid. If a patch contains custom operations (see
176
+ :class:`jsonpatch.JsonPatch`'s ``operations``), whose changes can't be undone,
177
+ the document is copied instead, and its contents are restored from the copy
178
+ if an operation fails; nested containers are then replaced by their copies.
179
+
180
+ Restoring the document exactly, with the same values, the same order of
181
+ object members and the same container objects, is guaranteed for documents
182
+ made of plain ``dict`` and ``list`` objects, which includes every document
183
+ parsed from JSON. Other containers are restored through their own item
184
+ operations, which is exact as long as these only change the item they are
185
+ given:
186
+
187
+ * Containers that change when they are merely read, such as a
188
+ ``collections.defaultdict``, which adds a missing key on lookup, are not
189
+ supported: looking up a location, testing a value or reading the ``from``
190
+ of a ``move`` or ``copy`` can add members to them that remain after a
191
+ rollback.
192
+ * The copy that patches with custom operations are restored from only
193
+ restores the items of mappings and sequences, not other state that a
194
+ custom operation can change, such as the attributes of objects in the
195
+ document or the ``maps`` of a ``collections.ChainMap``.
196
+
197
+
198
+ Ignoring Missing Locations
199
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
200
+
201
+ `RFC 6902 <https://tools.ietf.org/html/rfc6902#section-4.2>`_ requires a
202
+ ``remove`` to fail if the location it removes doesn't exist, and this library
203
+ follows it: such an operation raises ``JsonPatchPathNotFound``. A ``replace``
204
+ of a missing location, and a ``move`` or ``copy`` from one, raise it as well.
205
+
206
+ .. code-block:: python
207
+
208
+ >>> patch = [{'op': 'remove', 'path': '/data/another'}]
209
+ >>> try:
210
+ ... jsonpatch.apply_patch({'data': {}}, patch)
211
+ ... except jsonpatch.JsonPatchPathNotFound as ex:
212
+ ... print(ex, ex.op.location)
213
+ can't remove a non-existent object 'another' /data/another
214
+
215
+ Catching the exception around ``apply`` does not skip just that operation,
216
+ though: application stops, and the operations after it are not applied.
217
+
218
+ If removing a member that is already absent should count as success (an
219
+ idempotent ``remove``), the recommended way is a ``JsonPatch`` subclass that
220
+ uses its own ``remove`` operation. The ``operations`` attribute of a
221
+ ``JsonPatch`` class maps each operation name to the class implementing it:
222
+
223
+ .. code-block:: python
224
+
225
+ >>> from types import MappingProxyType
226
+ >>> class IdempotentRemoveOperation(jsonpatch.RemoveOperation):
227
+ ... def apply(self, obj):
228
+ ... try:
229
+ ... return super().apply(obj)
230
+ ... except jsonpatch.JsonPatchPathNotFound:
231
+ ... return obj # nothing to remove
232
+ >>> class IdempotentJsonPatch(jsonpatch.JsonPatch):
233
+ ... operations = MappingProxyType(dict(
234
+ ... jsonpatch.JsonPatch.operations,
235
+ ... remove=IdempotentRemoveOperation,
236
+ ... ))
237
+
238
+ >>> patch = IdempotentJsonPatch([
239
+ ... {'op': 'remove', 'path': '/data/another'},
240
+ ... {'op': 'add', 'path': '/data/new', 'value': 1},
241
+ ... ])
242
+ >>> patch.apply({'data': {}})
243
+ {'data': {'new': 1}}
244
+
245
+ Only a missing member or element is ignored. Other errors still raise, such
246
+ as a ``JsonPatchConflict`` for removing the whole document, or a
247
+ ``JsonPointerException`` if a parent of the location doesn't exist:
248
+
249
+ .. code-block:: python
250
+
251
+ >>> patch = IdempotentJsonPatch([{'op': 'remove', 'path': '/missing/key'}])
252
+ >>> patch.apply({'data': {}})
253
+ Traceback (most recent call last):
254
+ ...
255
+ jsonpointer.JsonPointerException: member 'missing' not found in {'data': {}}
256
+
257
+ Patches applied this way don't conform to RFC 6902, so only use this where
258
+ both sides of an exchange agree on it.
259
+
154
260
 
155
261
  Replacing the Whole Document
156
262
  ----------------------------
@@ -0,0 +1,148 @@
1
+ # Type stubs for jsonpatch.
2
+ #
3
+ # jsonpatch is a single-file module, and PEP 561 has no py.typed marker for
4
+ # those, so its types are shipped as this stub-only package in the same
5
+ # distribution. Keep it in sync with jsonpatch.py; CI runs mypy's stubtest to
6
+ # check that both agree.
7
+ #
8
+ # JSON documents are typed as Any: they can be any JSON value, and the module
9
+ # also accepts arbitrary Mapping / Sequence types, which a recursive JSON type
10
+ # would reject.
11
+
12
+ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
13
+ from typing import Any, ClassVar
14
+
15
+ # Re-exported, as jsonpatch.py imports them and users rely on that, e.g. to
16
+ # catch jsonpatch.JsonPointerException. stubtest does not check these, as
17
+ # they are defined in another module.
18
+ from jsonpointer import JsonPointer as JsonPointer
19
+ from jsonpointer import JsonPointerException as JsonPointerException
20
+ from typing_extensions import Self
21
+
22
+ __author__: str
23
+ __version__: str
24
+ __website__: str
25
+ __license__: str
26
+
27
+ # A single patch operation, e.g. {'op': 'add', 'path': '/a', 'value': 1}
28
+ _Operation = Mapping[str, Any]
29
+
30
+ class JsonPatchException(Exception):
31
+ # The failing operation: a PatchOperation, or the raw operation object if
32
+ # none could be constructed from it, or None.
33
+ op: Any
34
+ def __init__(self, *args: object, op: Any = None) -> None: ...
35
+
36
+ class InvalidJsonPatch(JsonPatchException): ...
37
+ class JsonPatchConflict(JsonPatchException): ...
38
+ class JsonPatchPathNotFound(JsonPatchConflict): ...
39
+ class JsonPatchTestFailed(JsonPatchException, AssertionError): ...
40
+
41
+ def multidict(ordered_pairs: Iterable[tuple[str, Any]]) -> dict[str, Any]: ...
42
+ def apply_patch(
43
+ doc: Any,
44
+ patch: str | bytes | Iterable[_Operation],
45
+ in_place: bool = False,
46
+ pointer_cls: type[JsonPointer] = ...,
47
+ atomic: bool = False,
48
+ ) -> Any: ...
49
+ def make_patch(
50
+ src: Any,
51
+ dst: Any,
52
+ pointer_cls: type[JsonPointer] = ...,
53
+ generate_test_ops: bool = False,
54
+ ) -> JsonPatch: ...
55
+
56
+ class PatchOperation:
57
+ pointer_cls: type[JsonPointer]
58
+ location: str
59
+ pointer: JsonPointer
60
+ operation: _Operation
61
+ def __init__(self, operation: _Operation, pointer_cls: type[JsonPointer] = ...) -> None: ...
62
+ def apply(self, obj: Any) -> Any: ...
63
+ def __hash__(self) -> int: ...
64
+ def __eq__(self, other: object) -> bool: ...
65
+ def __ne__(self, other: object) -> bool: ...
66
+ @property
67
+ def path(self) -> str: ...
68
+ @property
69
+ def key(self) -> int | str: ...
70
+ @key.setter
71
+ def key(self, value: int | str) -> None: ...
72
+ def get_part(self, index: int) -> int | str: ...
73
+ def set_part(self, index: int, value: int | str) -> None: ...
74
+
75
+ class RemoveOperation(PatchOperation): ...
76
+ class AddOperation(PatchOperation): ...
77
+ class ReplaceOperation(PatchOperation): ...
78
+
79
+ class MoveOperation(PatchOperation):
80
+ @property
81
+ def from_path(self) -> str: ...
82
+ @property
83
+ def from_key(self) -> int | str: ...
84
+ @from_key.setter
85
+ def from_key(self, value: int | str) -> None: ...
86
+ def get_from_part(self, index: int) -> int | str: ...
87
+ def set_from_part(self, index: int, value: int | str) -> None: ...
88
+
89
+ class TestOperation(PatchOperation): ...
90
+ class CopyOperation(PatchOperation): ...
91
+
92
+ class JsonPatch:
93
+ json_dumper: ClassVar[Callable[..., str]]
94
+ json_loader: ClassVar[Callable[..., Any]]
95
+ operations: ClassVar[Mapping[str, type[PatchOperation]]]
96
+ pointer_cls: type[JsonPointer]
97
+ patch: Sequence[_Operation]
98
+ def __init__(self, patch: Iterable[_Operation], pointer_cls: type[JsonPointer] = ...) -> None: ...
99
+ def __bool__(self) -> bool: ...
100
+ def __iter__(self) -> Iterator[_Operation]: ...
101
+ def __hash__(self) -> int: ...
102
+ def __eq__(self, other: object) -> bool: ...
103
+ def __ne__(self, other: object) -> bool: ...
104
+ __nonzero__ = __bool__
105
+ @classmethod
106
+ def from_string(
107
+ cls,
108
+ patch_str: str | bytes | bytearray,
109
+ loads: Callable[[Any], Any] | None = None,
110
+ pointer_cls: type[JsonPointer] = ...,
111
+ ) -> Self: ...
112
+ @classmethod
113
+ def from_diff(
114
+ cls,
115
+ src: Any,
116
+ dst: Any,
117
+ optimization: bool = True,
118
+ dumps: Callable[[Any], str] | None = None,
119
+ pointer_cls: type[JsonPointer] = ...,
120
+ generate_test_ops: bool = False,
121
+ ) -> Self: ...
122
+ def to_string(self, dumps: Callable[[Any], str] | None = None) -> str: ...
123
+ def apply(self, obj: Any, in_place: bool = False, atomic: bool = False) -> Any: ...
124
+
125
+ # Computes the operations for JsonPatch.from_diff; mostly an implementation
126
+ # detail, so its internal methods are typed loosely.
127
+ class DiffBuilder:
128
+ dumps: Callable[[Any], str]
129
+ pointer_cls: type[JsonPointer]
130
+ optimization: bool
131
+ generate_test_ops: bool
132
+ src_doc: Any
133
+ dst_doc: Any
134
+ def __init__(
135
+ self,
136
+ src_doc: Any,
137
+ dst_doc: Any,
138
+ dumps: Callable[[Any], str] = ...,
139
+ pointer_cls: type[JsonPointer] = ...,
140
+ optimization: bool = True,
141
+ generate_test_ops: bool = False,
142
+ ) -> None: ...
143
+ def store_index(self, value: Any, index: Any, st: int) -> None: ...
144
+ def take_index(self, value: Any, st: int) -> Any: ...
145
+ def insert(self, op: Any) -> Any: ...
146
+ def remove(self, index: Any) -> None: ...
147
+ def __iter__(self) -> Iterator[Any]: ...
148
+ def execute(self) -> Iterator[dict[str, Any]]: ...
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpatch
3
- Version: 1.40
3
+ Version: 1.42
4
4
  Summary: Apply JSON-Patches (RFC 6902)
5
5
  Home-page: https://github.com/stefankoegl/python-json-patch
6
6
  Author: Stefan Kögl
@@ -28,11 +28,12 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
28
28
  Classifier: Programming Language :: Python :: Implementation :: PyPy
29
29
  Classifier: Topic :: Software Development :: Libraries
30
30
  Classifier: Topic :: Utilities
31
+ Classifier: Typing :: Typed
31
32
  Requires-Python: >=3.10
32
33
  Description-Content-Type: text/markdown
33
34
  License-File: LICENSE
34
35
  License-File: AUTHORS
35
- Requires-Dist: jsonpointer>=3.2
36
+ Requires-Dist: jsonpointer>=3.8
36
37
  Dynamic: author
37
38
  Dynamic: author-email
38
39
  Dynamic: classifier
@@ -69,6 +70,20 @@ See source code for examples
69
70
  * CI: https://github.com/stefankoegl/python-json-patch/actions
70
71
  * Coveralls: https://coveralls.io/github/stefankoegl/python-json-patch
71
72
 
73
+ Type hints
74
+ ----------
75
+ jsonpatch ships type stubs (in the `jsonpatch-stubs` directory, as
76
+ jsonpatch.py is a single-file module), so type checkers such as mypy and
77
+ pyright work with it without further setup. JSON documents are typed as `Any`.
78
+
79
+ When changing the public API of jsonpatch.py, update
80
+ `jsonpatch-stubs/__init__.pyi` as well. These check that both agree, and that
81
+ typical usage in `typetests/usage.py` type-checks:
82
+
83
+ pip install mypy .
84
+ python -m mypy.stubtest --mypy-config-file pyproject.toml jsonpatch
85
+ cd typetests && mypy --config-file ../pyproject.toml usage.py
86
+
72
87
  Running external tests
73
88
  ----------------------
74
89
  To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_tests.py
@@ -16,9 +16,11 @@ doc/commandline.rst
16
16
  doc/index.rst
17
17
  doc/mod-jsonpatch.rst
18
18
  doc/tutorial.rst
19
+ jsonpatch-stubs/__init__.pyi
19
20
  jsonpatch.egg-info/PKG-INFO
20
21
  jsonpatch.egg-info/SOURCES.txt
21
22
  jsonpatch.egg-info/dependency_links.txt
22
23
  jsonpatch.egg-info/entry_points.txt
23
24
  jsonpatch.egg-info/requires.txt
24
- jsonpatch.egg-info/top_level.txt
25
+ jsonpatch.egg-info/top_level.txt
26
+ typetests/usage.py
@@ -0,0 +1 @@
1
+ jsonpointer>=3.8
@@ -1,2 +1,3 @@
1
1
  jsonpatch
2
+ jsonpatch-stubs
2
3
  jsonpatch_cli