Debian Codegraph @

src/libtmux/_internal/query_list.py

raw symbols SCIP
1 """Utilities for filtering or searching :class:`list` of objects / list data.
2
3 Note
4 ----
5 This is an internal API not covered by versioning policy.
6 """
7
8 from __future__ import annotations
9
10 import logging
11 import re
12 import typing as t
13 from collections.abc import Callable, Iterable, Mapping, Sequence
14
15 logger = logging.getLogger(__name__)
16
17 if t.TYPE_CHECKING:
18
19 class LookupProtocol(t.Protocol):
20 """Protocol for :class:`QueryList` filtering operators."""
21
22 def __call__(
23 self,
24 data: str | list[str] | Mapping[str, str],
25 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
26 ) -> bool:
27 """Return callback for :class:`QueryList` filtering operators."""
28 ...
29
30
31 T = t.TypeVar("T")
32
33 no_arg = object()
34
35
36 class MultipleObjectsReturned(Exception):
37 """The query returned multiple objects when only one was expected."""
38
39
40 class ObjectDoesNotExist(Exception):
41 """The requested object does not exist."""
42
43
44 def keygetter(
45 obj: Mapping[str, t.Any],
46 path: str,
47 ) -> None | t.Any | str | list[str] | Mapping[str, str]:
48 """Fetch values in objects and keys, supported nested data.
49
50 **With dictionaries**:
51
52 >>> keygetter({ "food": { "breakfast": "cereal" } }, "food")
53 {'breakfast': 'cereal'}
54
55 >>> keygetter({ "food": { "breakfast": "cereal" } }, "food__breakfast")
56 'cereal'
57
58 **With objects**:
59
60 >>> from typing import List, Optional
61 >>> from dataclasses import dataclass, field
62
63 >>> @dataclass()
64 ... class Food:
65 ... fruit: List[str] = field(default_factory=list)
66 ... breakfast: Optional[str] = None
67
68
69 >>> @dataclass()
70 ... class Restaurant:
71 ... place: str
72 ... city: str
73 ... state: str
74 ... food: Food = field(default_factory=Food)
75
76
77 >>> restaurant = Restaurant(
78 ... place="Largo",
79 ... city="Tampa",
80 ... state="Florida",
81 ... food=Food(
82 ... fruit=["banana", "orange"], breakfast="cereal"
83 ... )
84 ... )
85
86 >>> restaurant
87 Restaurant(place='Largo',
88 city='Tampa',
89 state='Florida',
90 food=Food(fruit=['banana', 'orange'], breakfast='cereal'))
91
92 >>> keygetter(restaurant, "food")
93 Food(fruit=['banana', 'orange'], breakfast='cereal')
94
95 >>> keygetter(restaurant, "food__breakfast")
96 'cereal'
97 """
98 try:
99 sub_fields = path.split("__")
100 dct = obj
101 for sub_field in sub_fields:
102 if isinstance(dct, dict):
103 dct = dct[sub_field]
104 elif hasattr(dct, sub_field):
105 dct = getattr(dct, sub_field)
106
107 except Exception:
108 logger.debug(
109 "key lookup failed for path: %s",
110 path,
111 exc_info=True,
112 )
113 return None
114
115 return dct
116
117
118 def parse_lookup(
119 obj: Mapping[str, t.Any],
120 path: str,
121 lookup: str,
122 ) -> t.Any | None:
123 """Check if field lookup key, e.g. "my__path__contains" has comparator, return val.
124
125 If comparator not used or value not found, return None.
126
127 >>> parse_lookup({ "food": "red apple" }, "food__istartswith", "__istartswith")
128 'red apple'
129
130 It can also look up objects:
131
132 >>> from dataclasses import dataclass
133
134 >>> @dataclass()
135 ... class Inventory:
136 ... food: str
137
138 >>> item = Inventory(food="red apple")
139
140 >>> item
141 Inventory(food='red apple')
142
143 >>> parse_lookup(item, "food__istartswith", "__istartswith")
144 'red apple'
145 """
146 try:
147 if isinstance(path, str) and isinstance(lookup, str) and path.endswith(lookup):
148 field_name = path.split(lookup, maxsplit=1)[0]
149 if field_name is not None:
150 return keygetter(obj, field_name)
151 except Exception:
152 logger.debug(
153 "lookup parsing failed for path: %s",
154 path,
155 exc_info=True,
156 )
157 return None
158
159
160 def lookup_exact(
161 data: str | list[str] | Mapping[str, str],
162 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
163 ) -> bool:
164 return rhs == data
165
166
167 def lookup_iexact(
168 data: str | list[str] | Mapping[str, str],
169 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
170 ) -> bool:
171 if not isinstance(rhs, str) or not isinstance(data, str):
172 return False
173
174 return rhs.lower() == data.lower()
175
176
177 def lookup_contains(
178 data: str | list[str] | Mapping[str, str],
179 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
180 ) -> bool:
181 if not isinstance(rhs, str) or not isinstance(data, (str, Mapping, list)):
182 return False
183
184 return rhs in data
185
186
187 def lookup_icontains(
188 data: str | list[str] | Mapping[str, str],
189 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
190 ) -> bool:
191 if not isinstance(rhs, str) or not isinstance(data, (str, Mapping, list)):
192 return False
193
194 if isinstance(data, str):
195 return rhs.lower() in data.lower()
196 if isinstance(data, Mapping):
197 return rhs.lower() in [k.lower() for k in data]
198
199 return False
200
201
202 def lookup_startswith(
203 data: str | list[str] | Mapping[str, str],
204 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
205 ) -> bool:
206 if not isinstance(rhs, str) or not isinstance(data, str):
207 return False
208
209 return data.startswith(rhs)
210
211
212 def lookup_istartswith(
213 data: str | list[str] | Mapping[str, str],
214 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
215 ) -> bool:
216 if not isinstance(rhs, str) or not isinstance(data, str):
217 return False
218
219 return data.lower().startswith(rhs.lower())
220
221
222 def lookup_endswith(
223 data: str | list[str] | Mapping[str, str],
224 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
225 ) -> bool:
226 if not isinstance(rhs, str) or not isinstance(data, str):
227 return False
228
229 return data.endswith(rhs)
230
231
232 def lookup_iendswith(
233 data: str | list[str] | Mapping[str, str],
234 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
235 ) -> bool:
236 if not isinstance(rhs, str) or not isinstance(data, str):
237 return False
238 return data.lower().endswith(rhs.lower())
239
240
241 def lookup_in(
242 data: str | list[str] | Mapping[str, str],
243 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
244 ) -> bool:
245 if isinstance(rhs, list):
246 return data in rhs
247
248 try:
249 if isinstance(rhs, str) and isinstance(data, Mapping):
250 return rhs in data
251 if isinstance(rhs, str) and isinstance(data, (str, list)):
252 return rhs in data
253 if isinstance(rhs, str) and isinstance(data, Mapping):
254 return rhs in data
255 # TODO: Add a deep Mappingionary matcher
256 # if isinstance(rhs, Mapping) and isinstance(data, Mapping):
257 # return rhs.items() not in data.items()
258 except Exception:
259 return False
260 return False
261
262
263 def lookup_nin(
264 data: str | list[str] | Mapping[str, str],
265 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
266 ) -> bool:
267 if isinstance(rhs, list):
268 return data not in rhs
269
270 try:
271 if isinstance(rhs, str) and isinstance(data, Mapping):
272 return rhs not in data
273 if isinstance(rhs, str) and isinstance(data, (str, list)):
274 return rhs not in data
275 if isinstance(rhs, str) and isinstance(data, Mapping):
276 return rhs not in data
277 # TODO: Add a deep Mappingionary matcher
278 # if isinstance(rhs, Mapping) and isinstance(data, Mapping):
279 # return rhs.items() not in data.items()
280 except Exception:
281 return False
282 return False
283
284
285 def lookup_regex(
286 data: str | list[str] | Mapping[str, str],
287 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
288 ) -> bool:
289 if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
290 return bool(re.search(rhs, data))
291 return False
292
293
294 def lookup_iregex(
295 data: str | list[str] | Mapping[str, str],
296 rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
297 ) -> bool:
298 if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
299 return bool(re.search(rhs, data, re.IGNORECASE))
300 return False
301
302
303 LOOKUP_NAME_MAP: Mapping[str, LookupProtocol] = {
304 "eq": lookup_exact,
305 "exact": lookup_exact,
306 "iexact": lookup_iexact,
307 "contains": lookup_contains,
308 "icontains": lookup_icontains,
309 "startswith": lookup_startswith,
310 "istartswith": lookup_istartswith,
311 "endswith": lookup_endswith,
312 "iendswith": lookup_iendswith,
313 "in": lookup_in,
314 "nin": lookup_nin,
315 "regex": lookup_regex,
316 "iregex": lookup_iregex,
317 }
318
319
320 class PKRequiredException(Exception):
321 def __init__(self, *args: object) -> None:
322 return super().__init__("items() require a pk_key exists")
323
324
325 class OpNotFound(ValueError):
326 def __init__(self, op: str, *args: object) -> None:
327 return super().__init__(f"{op} not in LOOKUP_NAME_MAP")
328
329
330 class QueryList(list[T], t.Generic[T]):
331 """Filter list of object/dictionaries. For small, local datasets.
332
333 *Experimental, unstable*.
334
335 **With dictionaries**:
336
337 >>> query = QueryList(
338 ... [
339 ... {
340 ... "place": "Largo",
341 ... "city": "Tampa",
342 ... "state": "Florida",
343 ... "foods": {"fruit": ["banana", "orange"], "breakfast": "cereal"},
344 ... },
345 ... {
346 ... "place": "Chicago suburbs",
347 ... "city": "Elmhurst",
348 ... "state": "Illinois",
349 ... "foods": {"fruit": ["apple", "cantelope"], "breakfast": "waffles"},
350 ... },
351 ... ]
352 ... )
353
354 >>> query.filter(place="Chicago suburbs")[0]['city']
355 'Elmhurst'
356 >>> query.filter(place__icontains="chicago")[0]['city']
357 'Elmhurst'
358 >>> query.filter(foods__breakfast="waffles")[0]['city']
359 'Elmhurst'
360 >>> query.filter(foods__fruit__in="cantelope")[0]['city']
361 'Elmhurst'
362 >>> query.filter(foods__fruit__in="orange")[0]['city']
363 'Tampa'
364
365 >>> query.filter(foods__fruit__in="apple")
366 [{'place': 'Chicago suburbs',
367 'city': 'Elmhurst',
368 'state': 'Illinois',
369 'foods':
370 {'fruit': ['apple', 'cantelope'], 'breakfast': 'waffles'}}]
371
372 >>> query.filter(foods__fruit__in="non_existent")
373 []
374
375 **With objects**:
376
377 >>> from typing import Any, Dict
378 >>> from dataclasses import dataclass, field
379
380 >>> @dataclass()
381 ... class Restaurant:
382 ... place: str
383 ... city: str
384 ... state: str
385 ... foods: Dict[str, Any]
386
387 >>> restaurant = Restaurant(
388 ... place="Largo",
389 ... city="Tampa",
390 ... state="Florida",
391 ... foods={
392 ... "fruit": ["banana", "orange"], "breakfast": "cereal"
393 ... }
394 ... )
395
396 >>> restaurant
397 Restaurant(place='Largo',
398 city='Tampa',
399 state='Florida',
400 foods={'fruit': ['banana', 'orange'], 'breakfast': 'cereal'})
401
402 >>> query = QueryList([restaurant])
403
404 >>> query.filter(foods__fruit__in="banana")
405 [Restaurant(place='Largo',
406 city='Tampa',
407 state='Florida',
408 foods={'fruit': ['banana', 'orange'], 'breakfast': 'cereal'})]
409
410 >>> query.filter(foods__fruit__in="banana")[0].city
411 'Tampa'
412
413 >>> query.get(foods__fruit__in="banana").city
414 'Tampa'
415
416 **With objects (nested)**:
417
418 >>> from typing import List, Optional
419 >>> from dataclasses import dataclass, field
420
421 >>> @dataclass()
422 ... class Food:
423 ... fruit: List[str] = field(default_factory=list)
424 ... breakfast: Optional[str] = None
425
426
427 >>> @dataclass()
428 ... class Restaurant:
429 ... place: str
430 ... city: str
431 ... state: str
432 ... food: Food = field(default_factory=Food)
433
434
435 >>> query = QueryList([
436 ... Restaurant(
437 ... place="Largo",
438 ... city="Tampa",
439 ... state="Florida",
440 ... food=Food(
441 ... fruit=["banana", "orange"], breakfast="cereal"
442 ... )
443 ... ),
444 ... Restaurant(
445 ... place="Chicago suburbs",
446 ... city="Elmhurst",
447 ... state="Illinois",
448 ... food=Food(
449 ... fruit=["apple", "cantelope"], breakfast="waffles"
450 ... )
451 ... )
452 ... ])
453
454 >>> query.filter(food__fruit__in="banana")
455 [Restaurant(place='Largo',
456 city='Tampa',
457 state='Florida',
458 food=Food(fruit=['banana', 'orange'], breakfast='cereal'))]
459
460 >>> query.filter(food__fruit__in="banana")[0].city
461 'Tampa'
462
463 >>> query.get(food__fruit__in="banana").city
464 'Tampa'
465
466 >>> query.filter(food__breakfast="waffles")
467 [Restaurant(place='Chicago suburbs',
468 city='Elmhurst',
469 state='Illinois',
470 food=Food(fruit=['apple', 'cantelope'], breakfast='waffles'))]
471
472 >>> query.filter(food__breakfast="waffles")[0].city
473 'Elmhurst'
474
475 >>> query.filter(food__breakfast="non_existent")
476 []
477 """
478
479 data: Sequence[T]
480 pk_key: str | None
481
482 def __init__(self, items: Iterable[T] | None = None) -> None:
483 super().__init__(items if items is not None else [])
484
485 def items(self) -> list[tuple[str, T]]:
486 if self.pk_key is None:
487 raise PKRequiredException
488 return [(getattr(item, self.pk_key), item) for item in self]
489
490 def __eq__(
491 self,
492 other: object,
493 ) -> bool:
494 data = other
495
496 if not isinstance(self, list) or not isinstance(data, list):
497 return False
498
499 if len(self) == len(data):
500 for a, b in zip(self, data, strict=False):
501 if isinstance(a, Mapping):
502 a_keys = a.keys()
503 if a.keys == b.keys():
504 for key in a_keys:
505 if abs(a[key] - b[key]) > 1:
506 return False
507 elif a != b:
508 return False
509
510 return True
511 return False
512
513 def filter(
514 self,
515 matcher: Callable[[T], bool] | T | None = None,
516 **kwargs: t.Any,
517 ) -> QueryList[T]:
518 """Filter list of objects."""
519
520 def filter_lookup(obj: t.Any) -> bool:
521 for path, v in kwargs.items():
522 try:
523 lhs, op = path.rsplit("__", 1)
524
525 if op not in LOOKUP_NAME_MAP:
526 raise OpNotFound(op=op)
527 except ValueError:
528 lhs = path
529 op = "exact"
530
531 assert op in LOOKUP_NAME_MAP
532 path = lhs
533 data = keygetter(obj, path)
534
535 if data is None or not LOOKUP_NAME_MAP[op](data, v):
536 return False
537
538 return True
539
540 if callable(matcher):
541 filter_ = matcher
542 elif matcher is not None:
543
544 def val_match(obj: str | list[t.Any] | T) -> bool:
545 if isinstance(matcher, list):
546 return obj in matcher
547 return bool(obj == matcher)
548
549 filter_ = val_match
550 else:
551 filter_ = filter_lookup
552
553 return self.__class__(k for k in self if filter_(k))
554
555 def get(
556 self,
557 matcher: Callable[[T], bool] | T | None = None,
558 default: t.Any | None = no_arg,
559 **kwargs: t.Any,
560 ) -> T | None:
561 """Retrieve one object.
562
563 Raises :exc:`MultipleObjectsReturned` if multiple objects found.
564
565 Raises :exc:`ObjectDoesNotExist` if no object found, unless ``default`` stated.
566 """
567 objs = self.filter(matcher=matcher, **kwargs)
568 if len(objs) > 1:
569 raise MultipleObjectsReturned
570 if len(objs) == 0:
571 if default == no_arg:
572 raise ObjectDoesNotExist
573 return default
574 return objs[0]