derafu-selector 1.0.0__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.
- derafu_selector/__init__.py +24 -0
- derafu_selector/py.typed +0 -0
- derafu_selector/selector.py +690 -0
- derafu_selector-1.0.0.dist-info/METADATA +94 -0
- derafu_selector-1.0.0.dist-info/RECORD +8 -0
- derafu_selector-1.0.0.dist-info/WHEEL +5 -0
- derafu_selector-1.0.0.dist-info/licenses/LICENSE +21 -0
- derafu_selector-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Read and write dictionaries using selectors.
|
|
3
|
+
|
|
4
|
+
Usage: ``from derafu_selector import selector``. The selector syntax is
|
|
5
|
+
described in the docstring of ``derafu_selector.selector``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from derafu_selector.selector import (
|
|
9
|
+
NotADictionaryError,
|
|
10
|
+
NotAssignableError,
|
|
11
|
+
NotIterableError,
|
|
12
|
+
UnsupportedOperatorError,
|
|
13
|
+
dictionary_read_case_insensitive,
|
|
14
|
+
selector,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
'NotADictionaryError',
|
|
19
|
+
'NotAssignableError',
|
|
20
|
+
'NotIterableError',
|
|
21
|
+
'UnsupportedOperatorError',
|
|
22
|
+
'dictionary_read_case_insensitive',
|
|
23
|
+
'selector',
|
|
24
|
+
]
|
derafu_selector/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Read and write dictionaries using "selectors".
|
|
3
|
+
|
|
4
|
+
A selector is a string that says which value to read from a dictionary (or
|
|
5
|
+
where to write it). Forms supported when reading:
|
|
6
|
+
|
|
7
|
+
- Simple and nested key: ``a``, ``a.b.c``.
|
|
8
|
+
- Element of a list: ``list[1]``.
|
|
9
|
+
- Element of a list of dictionaries matched by another key:
|
|
10
|
+
``list[key=value:result_key]``.
|
|
11
|
+
- Quoted literal strings and concatenation: ``"Total: "(a.b)``.
|
|
12
|
+
- Alternatives (the first non-empty value): ``a||b||"default"``.
|
|
13
|
+
- Ternary IF: ``((a) = "x" ? (b) : (c))``. Operators: ``=``, ``==``,
|
|
14
|
+
``!=``, ``<>``, ``>``, ``>=``, ``<``, ``<=``, ``contains``, ``length``
|
|
15
|
+
and ``is`` (``"None"`` or ``"not None"``).
|
|
16
|
+
- JSONPath (``$.a.b``) and JMESPath (``jmespath:a.b``) queries.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import operator
|
|
20
|
+
import re
|
|
21
|
+
from collections.abc import Callable, Iterable, Mapping, MutableMapping
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from typing import Literal, TypeIs
|
|
24
|
+
|
|
25
|
+
import jmespath
|
|
26
|
+
from jsonpath import jsonpath
|
|
27
|
+
|
|
28
|
+
# -----------------------------------------------------------------------------
|
|
29
|
+
# Exceptions
|
|
30
|
+
# -----------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class UnsupportedOperatorError(ValueError):
|
|
34
|
+
|
|
35
|
+
"""Ternary IF operator that cannot be evaluated."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, operator_name: str) -> None:
|
|
38
|
+
"""
|
|
39
|
+
Create the error with the given operator.
|
|
40
|
+
|
|
41
|
+
:param operator_name: Operator of the ternary IF.
|
|
42
|
+
"""
|
|
43
|
+
super().__init__(f'Unsupported operator: {operator_name}')
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class NotADictionaryError(AttributeError):
|
|
47
|
+
|
|
48
|
+
"""
|
|
49
|
+
A key was read or created on a value that is not a dictionary.
|
|
50
|
+
|
|
51
|
+
It is the ``AttributeError`` previously raised when calling ``.get()``
|
|
52
|
+
or ``.setdefault()`` on that value.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, value: object) -> None:
|
|
56
|
+
"""
|
|
57
|
+
Create the error with the value that is not a dictionary.
|
|
58
|
+
|
|
59
|
+
:param value: Value received.
|
|
60
|
+
"""
|
|
61
|
+
super().__init__(
|
|
62
|
+
f"'{type(value).__name__}' object is not a dictionary"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class NotAssignableError(TypeError):
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
A key was assigned on a value that is not a dictionary.
|
|
70
|
+
|
|
71
|
+
It is the ``TypeError`` previously raised when assigning on that value.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, value: object) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Create the error with the value that is not a dictionary.
|
|
77
|
+
|
|
78
|
+
:param value: Value received.
|
|
79
|
+
"""
|
|
80
|
+
super().__init__(
|
|
81
|
+
f"'{type(value).__name__}' object does not support key assignment"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class NotIterableError(TypeError):
|
|
86
|
+
|
|
87
|
+
"""
|
|
88
|
+
A list was expected and the value cannot be iterated.
|
|
89
|
+
|
|
90
|
+
It is the ``TypeError`` previously raised when iterating that value.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, value: object) -> None:
|
|
94
|
+
"""
|
|
95
|
+
Create the error with the value that cannot be iterated.
|
|
96
|
+
|
|
97
|
+
:param value: Value received.
|
|
98
|
+
"""
|
|
99
|
+
super().__init__(f"'{type(value).__name__}' object is not iterable")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# -----------------------------------------------------------------------------
|
|
103
|
+
# Selector parts
|
|
104
|
+
# -----------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class _Text:
|
|
109
|
+
|
|
110
|
+
"""Literal (quoted) string of a selector."""
|
|
111
|
+
|
|
112
|
+
value: str
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class _Selector:
|
|
117
|
+
|
|
118
|
+
"""Selector in parentheses; ``kind`` is ``if`` for a ternary IF."""
|
|
119
|
+
|
|
120
|
+
selector_id: str
|
|
121
|
+
kind: Literal['selector', 'if']
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class _OrOperator:
|
|
126
|
+
|
|
127
|
+
"""``||`` operator between selector parts."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
type _Part = _Text | _Selector | _OrOperator
|
|
131
|
+
|
|
132
|
+
# ternary IF comparisons, which are done between strings
|
|
133
|
+
_COMPARISONS: dict[str, Callable[[str, str], bool]] = {
|
|
134
|
+
'=': operator.eq,
|
|
135
|
+
'==': operator.eq,
|
|
136
|
+
'!=': operator.ne,
|
|
137
|
+
'<>': operator.ne,
|
|
138
|
+
'>': operator.gt,
|
|
139
|
+
'>=': operator.ge,
|
|
140
|
+
'<': operator.lt,
|
|
141
|
+
'<=': operator.le,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
# -----------------------------------------------------------------------------
|
|
145
|
+
# Type helpers
|
|
146
|
+
# -----------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _is_dict(value: object) -> TypeIs[dict[object, object]]:
|
|
150
|
+
"""
|
|
151
|
+
Tell whether a value is a ``dict``.
|
|
152
|
+
|
|
153
|
+
:param value: Value to check.
|
|
154
|
+
:return: True if it is a ``dict``.
|
|
155
|
+
:rtype: bool
|
|
156
|
+
"""
|
|
157
|
+
return isinstance(value, dict)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]:
|
|
161
|
+
"""
|
|
162
|
+
Tell whether a value is a dictionary (or a mapping) that can be read.
|
|
163
|
+
|
|
164
|
+
:param value: Value to check.
|
|
165
|
+
:return: True if it is a ``Mapping``.
|
|
166
|
+
:rtype: bool
|
|
167
|
+
"""
|
|
168
|
+
return isinstance(value, Mapping)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _is_mutable_mapping(
|
|
172
|
+
value: object,
|
|
173
|
+
) -> TypeIs[MutableMapping[object, object]]:
|
|
174
|
+
"""
|
|
175
|
+
Tell whether a value is a dictionary (or a mapping) that can be changed.
|
|
176
|
+
|
|
177
|
+
:param value: Value to check.
|
|
178
|
+
:return: True if it is a ``MutableMapping``.
|
|
179
|
+
:rtype: bool
|
|
180
|
+
"""
|
|
181
|
+
return isinstance(value, MutableMapping)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _is_list(value: object) -> TypeIs[list[object]]:
|
|
185
|
+
"""
|
|
186
|
+
Tell whether a value is a list.
|
|
187
|
+
|
|
188
|
+
:param value: Value to check.
|
|
189
|
+
:return: True if it is a ``list``.
|
|
190
|
+
:rtype: bool
|
|
191
|
+
"""
|
|
192
|
+
return isinstance(value, list)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _is_iterable(value: object) -> TypeIs[Iterable[object]]:
|
|
196
|
+
"""
|
|
197
|
+
Tell whether a value can be iterated.
|
|
198
|
+
|
|
199
|
+
:param value: Value to check.
|
|
200
|
+
:return: True if it is an ``Iterable``.
|
|
201
|
+
:rtype: bool
|
|
202
|
+
"""
|
|
203
|
+
return isinstance(value, Iterable)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _get(mapping: object, key: str, default: object = None) -> object:
|
|
207
|
+
"""
|
|
208
|
+
Read a key from a dictionary, like ``dict.get()``.
|
|
209
|
+
|
|
210
|
+
:param mapping: Dictionary to read from.
|
|
211
|
+
:param key: Key to read.
|
|
212
|
+
:param default: Value returned if the key does not exist.
|
|
213
|
+
:return: Value of the key or ``default``.
|
|
214
|
+
:raises NotADictionaryError: If ``mapping`` is not a dictionary.
|
|
215
|
+
"""
|
|
216
|
+
if not _is_mapping(mapping):
|
|
217
|
+
raise NotADictionaryError(mapping)
|
|
218
|
+
return mapping.get(key, default)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# -----------------------------------------------------------------------------
|
|
222
|
+
# Public functions
|
|
223
|
+
# -----------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def dictionary_read_case_insensitive[V](
|
|
227
|
+
dictionary: Mapping[str, V], key: str
|
|
228
|
+
) -> V | None:
|
|
229
|
+
"""
|
|
230
|
+
Read a key from a dictionary, ignoring upper and lower case.
|
|
231
|
+
|
|
232
|
+
:param dictionary: Dictionary to read from.
|
|
233
|
+
:param key: Key to look for.
|
|
234
|
+
:return: Value of the key, or None if it does not exist. If several keys
|
|
235
|
+
differ only in case, the last one wins.
|
|
236
|
+
"""
|
|
237
|
+
lowered = {k.lower(): v for k, v in dictionary.items()}
|
|
238
|
+
return lowered.get(key.lower())
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def selector(
|
|
242
|
+
dictionary: object,
|
|
243
|
+
selector_id: str | None,
|
|
244
|
+
value: object = None,
|
|
245
|
+
*,
|
|
246
|
+
force_write: bool = False,
|
|
247
|
+
debug: bool = False,
|
|
248
|
+
) -> object:
|
|
249
|
+
"""
|
|
250
|
+
Read from or write to a dictionary using a selector.
|
|
251
|
+
|
|
252
|
+
If ``value`` (or ``force_write``) is given, it writes; otherwise, it
|
|
253
|
+
reads.
|
|
254
|
+
|
|
255
|
+
:param dictionary: Dictionary to read from or write to. To write, it must
|
|
256
|
+
be a mutable dictionary.
|
|
257
|
+
:param selector_id: Selector (see the module docstring). If None, None is
|
|
258
|
+
returned and nothing is done.
|
|
259
|
+
:param value: Value to write. If None, it reads.
|
|
260
|
+
:param force_write: Write even if ``value`` is None (keyword-only).
|
|
261
|
+
:param debug: Raise the exceptions instead of returning None (read) or
|
|
262
|
+
False (write) (keyword-only).
|
|
263
|
+
:return: When reading, the value read (of any type, as in a JSON). When
|
|
264
|
+
writing, True if it was written and False if not.
|
|
265
|
+
"""
|
|
266
|
+
# without a selector, None is returned: it can come from a configuration
|
|
267
|
+
# or from a default value that is None
|
|
268
|
+
if selector_id is None:
|
|
269
|
+
return None
|
|
270
|
+
# if there is a value, it is a write to the dictionary
|
|
271
|
+
if value is not None or force_write:
|
|
272
|
+
try:
|
|
273
|
+
_selector_write(dictionary, selector_id, value)
|
|
274
|
+
# any error (from the data, JSONPath or JMESPath) means that it could
|
|
275
|
+
# not be written: this is the function's contract without debug
|
|
276
|
+
except Exception:
|
|
277
|
+
if debug:
|
|
278
|
+
raise
|
|
279
|
+
return False
|
|
280
|
+
return True
|
|
281
|
+
# if there is no value, and writing was not forced, it is a read
|
|
282
|
+
try:
|
|
283
|
+
return _selector_read_all(dictionary, selector_id)
|
|
284
|
+
# any error means that it could not be read: this is the function's
|
|
285
|
+
# contract without debug
|
|
286
|
+
except Exception:
|
|
287
|
+
if debug:
|
|
288
|
+
raise
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# -----------------------------------------------------------------------------
|
|
293
|
+
# Internal functions
|
|
294
|
+
# -----------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _selector_write(
|
|
298
|
+
dictionary: object, selector_id: str, value: object
|
|
299
|
+
) -> None:
|
|
300
|
+
"""
|
|
301
|
+
Write a value at the key path of a selector (``a.b.c``).
|
|
302
|
+
|
|
303
|
+
Intermediate keys that do not exist are created as dictionaries.
|
|
304
|
+
|
|
305
|
+
:param dictionary: Dictionary to write to.
|
|
306
|
+
:param selector_id: Path of keys separated by dots.
|
|
307
|
+
:param value: Value to write.
|
|
308
|
+
:raises NotADictionaryError: If an intermediate value is not a
|
|
309
|
+
dictionary.
|
|
310
|
+
:raises NotAssignableError: If the assignment target is not a dictionary.
|
|
311
|
+
"""
|
|
312
|
+
parts = selector_id.split('.')
|
|
313
|
+
n_parts = len(parts)
|
|
314
|
+
target = dictionary
|
|
315
|
+
for i, part in enumerate(parts):
|
|
316
|
+
if i == n_parts - 1:
|
|
317
|
+
if not _is_mutable_mapping(target):
|
|
318
|
+
raise NotAssignableError(target)
|
|
319
|
+
target[part] = value
|
|
320
|
+
else:
|
|
321
|
+
# if the key does not exist, a new dictionary is created in it
|
|
322
|
+
if not _is_mutable_mapping(target):
|
|
323
|
+
raise NotADictionaryError(target)
|
|
324
|
+
target = target.setdefault(part, {})
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _selector_read_all(dictionary: object, selector_id: str) -> object:
|
|
328
|
+
"""
|
|
329
|
+
Read a selector that may have strings, several selectors and ``||``.
|
|
330
|
+
|
|
331
|
+
:param dictionary: Dictionary to read from.
|
|
332
|
+
:param selector_id: Full selector.
|
|
333
|
+
:return: Value read. With ``||``, the first non-empty value is returned.
|
|
334
|
+
"""
|
|
335
|
+
# wrap the selector in parentheses if it does not start with one
|
|
336
|
+
if not selector_id.startswith('(') and not selector_id.startswith('"'):
|
|
337
|
+
selector_id = '(' + selector_id + ')'
|
|
338
|
+
parts = _selector_id_get_parts(selector_id)
|
|
339
|
+
# if there is only one part and it is not an OR operator, return its value
|
|
340
|
+
if len(parts) == 1:
|
|
341
|
+
part = parts[0]
|
|
342
|
+
if isinstance(part, _Selector):
|
|
343
|
+
if part.kind == 'if' or '||' not in part.selector_id:
|
|
344
|
+
return _selector_read(dictionary, part.selector_id)
|
|
345
|
+
elif isinstance(part, _Text):
|
|
346
|
+
return part.value
|
|
347
|
+
# process several parts or the presence of an OR operator
|
|
348
|
+
final_value: object = None
|
|
349
|
+
for part in parts:
|
|
350
|
+
if isinstance(part, _Text):
|
|
351
|
+
final_value = _concatenate_values(final_value, part.value)
|
|
352
|
+
elif isinstance(part, _Selector):
|
|
353
|
+
# look for possible OR operators and process them
|
|
354
|
+
value: object = None
|
|
355
|
+
or_value_found = False
|
|
356
|
+
for sub_selector in part.selector_id.split('||'):
|
|
357
|
+
value = _selector_read(dictionary, sub_selector)
|
|
358
|
+
if value not in (None, ''):
|
|
359
|
+
final_value = _concatenate_values(final_value, value)
|
|
360
|
+
or_value_found = True
|
|
361
|
+
break
|
|
362
|
+
# if no valid value was found, the last value found is used,
|
|
363
|
+
# which could be None or ''
|
|
364
|
+
if not or_value_found:
|
|
365
|
+
# in an OR without a value the OR result is always None
|
|
366
|
+
if '||' in part.selector_id:
|
|
367
|
+
value = None
|
|
368
|
+
final_value = _concatenate_values(final_value, value)
|
|
369
|
+
elif final_value is not None:
|
|
370
|
+
# OR operator between parts: if there is already a value, stop
|
|
371
|
+
break
|
|
372
|
+
return final_value
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _concatenate_values(current_value: object, new_value: object) -> object:
|
|
376
|
+
"""
|
|
377
|
+
Append a value to the accumulated result.
|
|
378
|
+
|
|
379
|
+
:param current_value: Accumulated result (None if there is none yet).
|
|
380
|
+
:param new_value: Value to append.
|
|
381
|
+
:return: ``new_value`` if there was no result; otherwise, both as a
|
|
382
|
+
string.
|
|
383
|
+
"""
|
|
384
|
+
if current_value is None:
|
|
385
|
+
return new_value
|
|
386
|
+
return str(current_value) + str(new_value)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _selector_id_get_parts(selector_id: str) -> list[_Part]:
|
|
390
|
+
"""
|
|
391
|
+
Split a selector into strings, selectors in parentheses and ``||``.
|
|
392
|
+
|
|
393
|
+
:param selector_id: Full selector.
|
|
394
|
+
:return: Parts of the selector, in order.
|
|
395
|
+
:rtype: list
|
|
396
|
+
"""
|
|
397
|
+
values: list[_Part] = []
|
|
398
|
+
start_index = 0
|
|
399
|
+
in_selector = False
|
|
400
|
+
in_string = False
|
|
401
|
+
depth = 0
|
|
402
|
+
for index, char in enumerate(selector_id):
|
|
403
|
+
if char == '(' and not in_string:
|
|
404
|
+
depth += 1
|
|
405
|
+
if not in_selector:
|
|
406
|
+
in_selector = True
|
|
407
|
+
start_index = index
|
|
408
|
+
elif char == ')' and not in_string:
|
|
409
|
+
depth -= 1
|
|
410
|
+
if in_selector and depth == 0:
|
|
411
|
+
in_selector = False
|
|
412
|
+
sub_id = selector_id[start_index + 1 : index]
|
|
413
|
+
values.append(
|
|
414
|
+
_Selector(sub_id, 'if' if '?' in sub_id else 'selector')
|
|
415
|
+
)
|
|
416
|
+
start_index = index + 1
|
|
417
|
+
elif char == '"' and not in_selector:
|
|
418
|
+
in_string = not in_string
|
|
419
|
+
if not in_string:
|
|
420
|
+
values.append(_Text(selector_id[start_index + 1 : index]))
|
|
421
|
+
start_index = index + 1
|
|
422
|
+
elif (
|
|
423
|
+
char == '|'
|
|
424
|
+
and index < len(selector_id) - 1
|
|
425
|
+
and selector_id[index + 1] == '|'
|
|
426
|
+
and not in_string
|
|
427
|
+
and not in_selector
|
|
428
|
+
and depth == 0
|
|
429
|
+
):
|
|
430
|
+
values.append(_OrOperator())
|
|
431
|
+
start_index = index + 2
|
|
432
|
+
return values
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _selector_read(dictionary: object, selector_id: str) -> object:
|
|
436
|
+
"""
|
|
437
|
+
Read a simple, list, dependent, IF, JSONPath or JMESPath selector.
|
|
438
|
+
|
|
439
|
+
:param dictionary: Dictionary (or value) to read from.
|
|
440
|
+
:param selector_id: Selector without concatenations.
|
|
441
|
+
:return: Value read, or None if it does not exist or the selector is not
|
|
442
|
+
valid.
|
|
443
|
+
"""
|
|
444
|
+
selector_id = selector_id.strip()
|
|
445
|
+
if not selector_id:
|
|
446
|
+
return dictionary
|
|
447
|
+
# malformed selector (it cannot end with a dot)
|
|
448
|
+
if selector_id.endswith('.'):
|
|
449
|
+
return None
|
|
450
|
+
# literal string: returned without quotes
|
|
451
|
+
if selector_id.startswith('"') and selector_id.endswith('"'):
|
|
452
|
+
return selector_id.strip('"')
|
|
453
|
+
return _selector_read_kind(dictionary, selector_id)
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _selector_read_kind(dictionary: object, selector_id: str) -> object:
|
|
457
|
+
"""
|
|
458
|
+
Detect the type of a selector and read it.
|
|
459
|
+
|
|
460
|
+
:param dictionary: Dictionary (or value) to read from.
|
|
461
|
+
:param selector_id: Selector without concatenations or literal strings.
|
|
462
|
+
:return: Value read, or None if the selector matches no type.
|
|
463
|
+
"""
|
|
464
|
+
part, _, next_id = selector_id.partition('.')
|
|
465
|
+
result: object = None
|
|
466
|
+
# simple selector: value of a key
|
|
467
|
+
if match := re.fullmatch(r'^(\w+)$', part):
|
|
468
|
+
result = _selector_read_simple(dictionary, match.group(1), next_id)
|
|
469
|
+
# dependent selector: value in a list of dictionaries matched by another
|
|
470
|
+
# key
|
|
471
|
+
elif match := re.fullmatch(r'^(\w+)\[(\w+)=([\w\s\-]+):(\w+)\]$', part):
|
|
472
|
+
key, required_key, required_value, dependent_key = (
|
|
473
|
+
match.groups()
|
|
474
|
+
)
|
|
475
|
+
result = _selector_read_dependent(
|
|
476
|
+
dictionary,
|
|
477
|
+
key,
|
|
478
|
+
required_key,
|
|
479
|
+
required_value,
|
|
480
|
+
dependent_key,
|
|
481
|
+
next_id,
|
|
482
|
+
)
|
|
483
|
+
# list selector: element of a list in a key
|
|
484
|
+
elif match := re.fullmatch(r'^(\w+)\[(\d+)\]$', part):
|
|
485
|
+
key, index = match.groups()
|
|
486
|
+
result = _selector_read_array(dictionary, key, index, next_id)
|
|
487
|
+
# ternary IF
|
|
488
|
+
elif match := re.fullmatch(
|
|
489
|
+
r'\((.+?)\)\s*(\S+)\s*\"(.*?)\"\s*\?\s*\((.+?)\)\s*:\s*\((.+?)\)',
|
|
490
|
+
selector_id,
|
|
491
|
+
):
|
|
492
|
+
condition, operator_name, value, if_true, if_false = match.groups()
|
|
493
|
+
result = _selector_read_if(
|
|
494
|
+
dictionary, condition, operator_name, value, if_true, if_false
|
|
495
|
+
)
|
|
496
|
+
# JSONPath expression
|
|
497
|
+
elif selector_id.startswith('$.'):
|
|
498
|
+
result = _selector_read_jsonpath(dictionary, selector_id)
|
|
499
|
+
# JMESPath expression
|
|
500
|
+
elif selector_id.startswith('jmespath:'):
|
|
501
|
+
result = _selector_read_jmespath(dictionary, selector_id)
|
|
502
|
+
# if it matches no type, the requested selector could not be processed
|
|
503
|
+
return result
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _continue_reading(value: object, next_id: str) -> object:
|
|
507
|
+
"""
|
|
508
|
+
Keep reading inside a value if it is a dictionary and selector remains.
|
|
509
|
+
|
|
510
|
+
:param value: Value read at the current level.
|
|
511
|
+
:param next_id: Rest of the selector.
|
|
512
|
+
:return: Final value.
|
|
513
|
+
"""
|
|
514
|
+
return (
|
|
515
|
+
_selector_read(value, next_id)
|
|
516
|
+
if _is_dict(value) and next_id
|
|
517
|
+
else value
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _selector_read_simple(
|
|
522
|
+
dictionary: object, key: str, next_id: str
|
|
523
|
+
) -> object:
|
|
524
|
+
"""
|
|
525
|
+
Read a key and, if needed, continue with the rest of the selector.
|
|
526
|
+
|
|
527
|
+
:param dictionary: Dictionary to read from.
|
|
528
|
+
:param key: Key to read.
|
|
529
|
+
:param next_id: Rest of the selector.
|
|
530
|
+
:return: Value read.
|
|
531
|
+
"""
|
|
532
|
+
return _continue_reading(_get(dictionary, key), next_id)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _selector_read_dependent(
|
|
536
|
+
dictionary: object,
|
|
537
|
+
dictionary_key: str,
|
|
538
|
+
required_key: str,
|
|
539
|
+
required_value: str,
|
|
540
|
+
dependent_key: str,
|
|
541
|
+
next_id: str,
|
|
542
|
+
) -> object:
|
|
543
|
+
"""
|
|
544
|
+
Read ``dependent_key`` from the first element matching ``required_key``.
|
|
545
|
+
|
|
546
|
+
:param dictionary: Dictionary to read from.
|
|
547
|
+
:param dictionary_key: Key holding the list of dictionaries.
|
|
548
|
+
:param required_key: Key compared in each element.
|
|
549
|
+
:param required_value: Value looked for (compared as a string).
|
|
550
|
+
:param dependent_key: Key read from the matching element.
|
|
551
|
+
:param next_id: Rest of the selector.
|
|
552
|
+
:return: Value read, or None if no element matches.
|
|
553
|
+
:raises NotIterableError: If the key does not hold a list.
|
|
554
|
+
"""
|
|
555
|
+
array_list = _get(dictionary, dictionary_key, [])
|
|
556
|
+
if not _is_iterable(array_list):
|
|
557
|
+
raise NotIterableError(array_list)
|
|
558
|
+
for element in array_list:
|
|
559
|
+
if str(_get(element, required_key)) == str(required_value) and (
|
|
560
|
+
_is_mapping(element) and dependent_key in element
|
|
561
|
+
):
|
|
562
|
+
return _continue_reading(element[dependent_key], next_id)
|
|
563
|
+
return None
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _selector_read_array(
|
|
567
|
+
dictionary: object, array_key: str, array_index: str, next_id: str
|
|
568
|
+
) -> object:
|
|
569
|
+
"""
|
|
570
|
+
Read an element of a list and, if needed, continue with the selector.
|
|
571
|
+
|
|
572
|
+
:param dictionary: Dictionary to read from.
|
|
573
|
+
:param array_key: Key holding the list.
|
|
574
|
+
:param array_index: Index of the element (as a string).
|
|
575
|
+
:param next_id: Rest of the selector.
|
|
576
|
+
:return: Value read, or None if there is no list or the index does not
|
|
577
|
+
exist.
|
|
578
|
+
"""
|
|
579
|
+
array = _get(dictionary, array_key, [])
|
|
580
|
+
if _is_list(array) and len(array) > int(array_index):
|
|
581
|
+
return _continue_reading(array[int(array_index)], next_id)
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _selector_read_if(
|
|
586
|
+
dictionary: object,
|
|
587
|
+
condition_selector: str,
|
|
588
|
+
operator_name: str,
|
|
589
|
+
value: str,
|
|
590
|
+
true_selector: str,
|
|
591
|
+
false_selector: str,
|
|
592
|
+
) -> object:
|
|
593
|
+
"""
|
|
594
|
+
Read a ternary IF: evaluate the condition and read one of two selectors.
|
|
595
|
+
|
|
596
|
+
:param dictionary: Dictionary to read from.
|
|
597
|
+
:param condition_selector: Selector of the condition value.
|
|
598
|
+
:param operator_name: Operator of the condition.
|
|
599
|
+
:param value: Value compared against.
|
|
600
|
+
:param true_selector: Selector read if the condition holds.
|
|
601
|
+
:param false_selector: Selector read if it does not.
|
|
602
|
+
:return: Value read, or None if the condition could not be evaluated.
|
|
603
|
+
"""
|
|
604
|
+
condition_value = _selector_read_all(dictionary, condition_selector)
|
|
605
|
+
try:
|
|
606
|
+
true_or_false = _if_evaluate_condition(
|
|
607
|
+
condition_value, operator_name.strip(), value.strip('"')
|
|
608
|
+
)
|
|
609
|
+
except ValueError:
|
|
610
|
+
return None
|
|
611
|
+
if true_or_false:
|
|
612
|
+
return _selector_read_all(dictionary, true_selector)
|
|
613
|
+
return _selector_read_all(dictionary, false_selector)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _if_evaluate_condition(
|
|
617
|
+
value_a: object, operator_name: str, value_b: str
|
|
618
|
+
) -> bool:
|
|
619
|
+
"""
|
|
620
|
+
Evaluate the condition of a ternary IF.
|
|
621
|
+
|
|
622
|
+
Comparisons (``=``, ``>``, etc.) are done between strings.
|
|
623
|
+
|
|
624
|
+
:param value_a: Value read with the condition selector.
|
|
625
|
+
:param operator_name: Operator.
|
|
626
|
+
:param value_b: Value compared against.
|
|
627
|
+
:return: Result of the condition.
|
|
628
|
+
:rtype: bool
|
|
629
|
+
:raises UnsupportedOperatorError: If the operator does not exist, or if
|
|
630
|
+
it cannot be applied to the value (``length`` on something that is
|
|
631
|
+
neither a list nor a string, or ``is`` with something other than
|
|
632
|
+
``None`` or ``not None``).
|
|
633
|
+
:raises ValueError: If ``length`` receives a length that is not a number.
|
|
634
|
+
"""
|
|
635
|
+
comparison = _COMPARISONS.get(operator_name)
|
|
636
|
+
if comparison is not None:
|
|
637
|
+
return comparison(str(value_a), str(value_b))
|
|
638
|
+
# contains (for lists and strings)
|
|
639
|
+
if operator_name == 'contains':
|
|
640
|
+
if _is_list(value_a):
|
|
641
|
+
return value_b in [str(item) for item in value_a]
|
|
642
|
+
return value_b in str(value_a)
|
|
643
|
+
# length (for strings and lists)
|
|
644
|
+
if operator_name == 'length' and (
|
|
645
|
+
_is_list(value_a) or isinstance(value_a, str)
|
|
646
|
+
):
|
|
647
|
+
return len(value_a) == int(value_b)
|
|
648
|
+
# "is" operator: "None" or "not None"
|
|
649
|
+
if operator_name == 'is' and value_b in {'None', 'not None'}:
|
|
650
|
+
return (value_a is None) == (value_b == 'None')
|
|
651
|
+
# unsupported operator (or not applicable to the value)
|
|
652
|
+
raise UnsupportedOperatorError(operator_name)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def _selector_read_jsonpath(dictionary: object, query: str) -> object:
|
|
656
|
+
"""
|
|
657
|
+
Read a JSONPath expression (``$.a.b``).
|
|
658
|
+
|
|
659
|
+
:param dictionary: Dictionary to read from.
|
|
660
|
+
:param query: JSONPath expression.
|
|
661
|
+
:return: Value read; if there is a single result, that value; if there
|
|
662
|
+
are no results, None.
|
|
663
|
+
"""
|
|
664
|
+
result = jsonpath(dictionary, query)
|
|
665
|
+
# jsonpath returns False when there are no matches
|
|
666
|
+
if result is False:
|
|
667
|
+
return None
|
|
668
|
+
# a list with a single element is returned as that element
|
|
669
|
+
if len(result) == 1:
|
|
670
|
+
return result[0]
|
|
671
|
+
return result
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def _selector_read_jmespath(dictionary: object, query: str) -> object:
|
|
675
|
+
"""
|
|
676
|
+
Read a JMESPath expression (``jmespath:a.b``).
|
|
677
|
+
|
|
678
|
+
:param dictionary: Dictionary to read from.
|
|
679
|
+
:param query: Expression with the ``jmespath:`` prefix.
|
|
680
|
+
:return: Value read; if there is a single result, that value; if there
|
|
681
|
+
are no results, None.
|
|
682
|
+
"""
|
|
683
|
+
result: object = jmespath.search(
|
|
684
|
+
query.replace('jmespath:', '', 1), dictionary
|
|
685
|
+
)
|
|
686
|
+
if result is None or (_is_list(result) and not result):
|
|
687
|
+
return None
|
|
688
|
+
if _is_list(result) and len(result) == 1:
|
|
689
|
+
return result[0]
|
|
690
|
+
return result
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: derafu-selector
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Read and write dictionaries using selectors (paths, IF, JSONPath and JMESPath).
|
|
5
|
+
Author: Derafu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/derafu/selector-python
|
|
8
|
+
Project-URL: Issues, https://github.com/derafu/selector-python/issues
|
|
9
|
+
Keywords: dictionary,selector,jsonpath,jmespath,json
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Topic :: Text Processing
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.13
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: jmespath>=1.1.0
|
|
25
|
+
Requires-Dist: jsonpath>=0.82.2
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# derafu-selector
|
|
29
|
+
|
|
30
|
+
Read and write dictionaries using selectors. The library does not depend on
|
|
31
|
+
Django.
|
|
32
|
+
|
|
33
|
+
Requires Python 3.13 or newer; tested on 3.13, 3.14 and 3.15.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install derafu-selector
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from derafu_selector import selector
|
|
45
|
+
|
|
46
|
+
data = {'issuer': {'tax_id': 76192083, 'name': 'ACME'}, 'type': 33}
|
|
47
|
+
|
|
48
|
+
selector(data, 'issuer.tax_id') # 76192083
|
|
49
|
+
selector(data, 'issuer.activity||"no activity"') # 'no activity'
|
|
50
|
+
selector(data, 'issuer.activity', 'Services') # True: writes the value
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Without `value` it reads: it returns the value, or `None` if it could not be
|
|
54
|
+
read. With `value` it writes: it returns `True` or `False`. With `debug=True`
|
|
55
|
+
the exceptions are raised instead of returning `None` or `False`, for example
|
|
56
|
+
`NotADictionaryError` (an `AttributeError`) or `NotAssignableError` and
|
|
57
|
+
`NotIterableError` (both `TypeError`). `force_write` and `debug` are
|
|
58
|
+
keyword-only.
|
|
59
|
+
|
|
60
|
+
## Selectors
|
|
61
|
+
|
|
62
|
+
| Form | Example |
|
|
63
|
+
|---|---|
|
|
64
|
+
| Simple and nested key | `a`, `a.b.c` |
|
|
65
|
+
| Element of a list | `list[1]` |
|
|
66
|
+
| Element of a list of dictionaries matched by another key | `list[key=value:result_key]` |
|
|
67
|
+
| Quoted strings and concatenation | `"Total: "(a.b)` |
|
|
68
|
+
| Alternatives (the first non-empty value) | `a\|\|b\|\|"default"` |
|
|
69
|
+
| Ternary IF | `((a) = "x" ? (b) : (c))` |
|
|
70
|
+
| JSONPath | `$.a.b` |
|
|
71
|
+
| JMESPath | `jmespath:a.b` |
|
|
72
|
+
|
|
73
|
+
IF operators: `=`, `==`, `!=`, `<>`, `>`, `>=`, `<`, `<=`, `contains`,
|
|
74
|
+
`length` and `is` (`"None"` or `"not None"`).
|
|
75
|
+
|
|
76
|
+
It also includes `dictionary_read_case_insensitive()`, which reads a key
|
|
77
|
+
ignoring upper and lower case.
|
|
78
|
+
|
|
79
|
+
## Development
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
make install-dev PYTHON=python3.15 # creates venv/ with the library and tools
|
|
83
|
+
make check # ruff, mypy, pyright and pytest
|
|
84
|
+
make build # builds dist/ and checks it with twine
|
|
85
|
+
make upload # builds dist/ and publishes it on PyPI
|
|
86
|
+
make docs # builds the Sphinx docs in docs/_build/html
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`typings/jsonpath.pyi` provides the type stubs for `jsonpath`, which ships
|
|
90
|
+
without them.
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT. See [LICENSE](https://github.com/derafu/selector-python/blob/main/LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
derafu_selector/__init__.py,sha256=XBPrtJ8Bh45VTWo65zNXzI4emyh4fnRMVqrVsKzxF4g,561
|
|
2
|
+
derafu_selector/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
derafu_selector/selector.py,sha256=UUCTrTFYpGgYE61PwJp8bZ2kfHRLoFJzuXT7ORNJRkE,22878
|
|
4
|
+
derafu_selector-1.0.0.dist-info/licenses/LICENSE,sha256=wkUIn63J2GnKY5NquvcTp0OTryf6HJvoljUWNsOCjeU,1117
|
|
5
|
+
derafu_selector-1.0.0.dist-info/METADATA,sha256=z06R8Rj3lLGFZ-Wtqas_G8mlUYm1-p40HYayWh-GUUc,3288
|
|
6
|
+
derafu_selector-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
derafu_selector-1.0.0.dist-info/top_level.txt,sha256=_Gx_ECn4wRkJglDiGVL6rGAU1ZCLiWoRGyZrnBo1beY,16
|
|
8
|
+
derafu_selector-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Esteban De La Fuente Rubio / Derafu <https://www.derafu.org>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
derafu_selector
|