Coverage for src/toolbox_python/checkers.py: 100%
73 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-13 07:24 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-13 07:24 +0000
1# ============================================================================ #
2# #
3# Title: Checkers #
4# Purpose: Check certain values against other objects. #
5# #
6# ============================================================================ #
9# ---------------------------------------------------------------------------- #
10# #
11# Setup ####
12# #
13# ---------------------------------------------------------------------------- #
16## --------------------------------------------------------------------------- #
17## Imports ####
18## --------------------------------------------------------------------------- #
21# ## Python StdLib Imports ----
22from typing import Any, Union
24# ## Python Third Party Imports ----
25from typeguard import typechecked
27# ## Local First Party Imports ----
28from toolbox_python.collection_types import any_collection, scalar, str_collection
31## --------------------------------------------------------------------------- #
32## Exports ####
33## --------------------------------------------------------------------------- #
36__all__: list[str] = [
37 "all_elements_contains",
38 "any_element_contains",
39 "assert_all_in",
40 "assert_all_type",
41 "assert_all_values_in_iterable",
42 "assert_all_values_of_type",
43 "assert_any_in",
44 "assert_any_type",
45 "assert_any_values_in_iterable",
46 "assert_in",
47 "assert_type",
48 "assert_value_in_iterable",
49 "assert_value_of_type",
50 "get_elements_containing",
51 "is_all_in",
52 "is_all_type",
53 "is_all_values_in_iterable",
54 "is_all_values_of_type",
55 "is_any_in",
56 "is_any_type",
57 "is_any_values_in_iterable",
58 "is_in",
59 "is_type",
60 "is_value_in_iterable",
61 "is_value_of_type",
62]
65# ---------------------------------------------------------------------------- #
66# #
67# Main Section ####
68# #
69# ---------------------------------------------------------------------------- #
72## --------------------------------------------------------------------------- #
73## `is_*()` functions ####
74## --------------------------------------------------------------------------- #
77def is_value_of_type(
78 value: Any,
79 check_type: Union[type, tuple[type, ...]],
80) -> bool:
81 """
82 !!! summary "Summary"
83 Check if a given value is of a specified type or types.
85 ???+ info "Details"
86 This function is used to verify if a given value matches a specified type or any of the types in a tuple of types.
88 Params:
89 value (Any):
90 The value to check.
91 check_type (Union[type, tuple[type]]):
92 The type or tuple of types to check against.
94 Returns:
95 (bool):
96 `#!py True` if the value is of the specified type or one of the specified types; `#!py False` otherwise.
98 ???+ example "Examples"
100 Check if a value is of a specific type:
102 ```{.py .python linenums="1" title="Prepare data"}
103 >>> value = 42
104 >>> check_type = int
105 ```
107 ```{.py .python linenums="1" title="Example 1: Check if value is of type `#!py int`"}
108 >>> is_value_of_type(value, check_type)
109 ```
110 <div class="result" markdown>
111 ```{.sh .shell title="Output"}
112 True
113 ```
114 !!! success "Conclusion: The value is of type `#!py int`."
116 </div>
118 ```{.py .python linenums="1" title="Example 2: Check if value is of type `#!py str`"}
119 >>> is_value_of_type(value, str)
120 ```
121 <div class="result" markdown>
122 ```{.sh .shell title="Output"}
123 False
124 ```
125 !!! failure "Conclusion: The value is not of type `#!py str`."
127 </div>
129 ??? tip "See Also"
130 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
131 - [`is_type()`][toolbox_python.checkers.is_type]
132 """
133 return isinstance(value, check_type)
136def is_all_values_of_type(
137 values: any_collection,
138 check_type: Union[type, tuple[type, ...]],
139) -> bool:
140 """
141 !!! summary "Summary"
142 Check if all values in an iterable are of a specified type or types.
144 ???+ info "Details"
145 This function is used to verify if all values in a given iterable match a specified type or any of the types in a tuple of types.
147 Params:
148 values (any_collection):
149 The iterable containing values to check.
150 check_type (Union[type, tuple[type]]):
151 The type or tuple of types to check against.
153 Returns:
154 (bool):
155 `#!py True` if all values are of the specified type or one of the specified types; `#!py False` otherwise.
157 ???+ example "Examples"
159 Check if all values in an iterable are of a specific type:
161 ```{.py .python linenums="1" title="Prepare data"}
162 >>> values = [1, 2, 3]
163 >>> check_type = int
164 ```
166 ```{.py .python linenums="1" title="Example 1: Check if all values are of type `#!py int`"}
167 >>> is_all_values_of_type(values, check_type)
168 ```
169 <div class="result" markdown>
170 ```{.sh .shell title="Output"}
171 True
172 ```
173 !!! success "Conclusion: All values are of type `#!py int`."
175 </div>
177 ```{.py .python linenums="1" title="Example 2: Check if all values are of type `#!py str`"}
178 >>> is_all_values_of_type(values, str)
179 ```
180 <div class="result" markdown>
181 ```{.sh .shell title="Output"}
182 False
183 ```
184 !!! failure "Conclusion: Not all values are of type `#!py str`."
186 </div>
188 ??? tip "See Also"
189 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
190 - [`is_all_values_of_type()`][toolbox_python.checkers.is_all_values_of_type]
191 - [`is_type()`][toolbox_python.checkers.is_type]
192 - [`is_all_type()`][toolbox_python.checkers.is_all_type]
193 """
194 return all(isinstance(value, check_type) for value in values)
197def is_any_values_of_type(
198 values: any_collection,
199 check_type: Union[type, tuple[type, ...]],
200) -> bool:
201 """
202 !!! summary "Summary"
203 Check if any value in an iterable is of a specified type or types.
205 ???+ info "Details"
206 This function is used to verify if any value in a given iterable matches a specified type or any of the types in a tuple of types.
208 Params:
209 values (any_collection):
210 The iterable containing values to check.
211 check_type (Union[type, tuple[type]]):
212 The type or tuple of types to check against.
214 Returns:
215 (bool):
216 `#!py True` if any value is of the specified type or one of the specified types; `#!py False` otherwise.
218 ???+ example "Examples"
220 Check if any value in an iterable is of a specific type:
222 ```{.py .python linenums="1" title="Prepare data"}
223 >>> values = [1, 'a', 3.0]
224 >>> check_type = str
225 ```
227 ```{.py .python linenums="1" title="Example 1: Check if any value is of type `#!py str`"}
228 >>> is_any_values_of_type(values, check_type)
229 ```
230 <div class="result" markdown>
231 ```{.sh .shell title="Output"}
232 True
233 ```
234 !!! success "Conclusion: At least one value is of type `#!py str`."
236 </div>
238 ```{.py .python linenums="1" title="Example 2: Check if any value is of type `#!py dict`"}
239 >>> is_any_values_of_type(values, dict)
240 ```
241 <div class="result" markdown>
242 ```{.sh .shell title="Output"}
243 False
244 ```
245 !!! failure "Conclusion: No values are of type `#!py dict`."
247 </div>
249 ??? tip "See Also"
250 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
251 - [`is_any_values_of_type()`][toolbox_python.checkers.is_any_values_of_type]
252 - [`is_type()`][toolbox_python.checkers.is_type]
253 - [`is_any_type()`][toolbox_python.checkers.is_any_type]
254 """
255 return any(isinstance(value, check_type) for value in values)
258def is_value_in_iterable(
259 value: scalar,
260 iterable: any_collection,
261) -> bool:
262 """
263 !!! summary "Summary"
264 Check if a given value is present in an iterable.
266 ???+ info "Details"
267 This function is used to verify if a given value exists within an iterable such as a list, tuple, or set.
269 Params:
270 value (scalar):
271 The value to check.
272 iterable (any_collection):
273 The iterable to check within.
275 Returns:
276 (bool):
277 `#!py True` if the value is found in the iterable; `#!py False` otherwise.
279 ???+ example "Examples"
281 Check if a value is in an iterable:
283 ```{.py .python linenums="1" title="Prepare data"}
284 >>> value = 2
285 >>> iterable = [1, 2, 3]
286 ```
288 ```{.py .python linenums="1" title="Example 1: Check if value is in the iterable"}
289 >>> is_value_in_iterable(value, iterable)
290 ```
291 <div class="result" markdown>
292 ```{.sh .shell title="Output"}
293 True
294 ```
295 !!! success "Conclusion: The value is in the iterable."
297 </div>
299 ```{.py .python linenums="1" title="Example 2: Check if value is not in the iterable"}
300 >>> is_value_in_iterable(4, iterable)
301 ```
302 <div class="result" markdown>
303 ```{.sh .shell title="Output"}
304 False
305 ```
306 !!! failure "Conclusion: The value is not in the iterable."
308 </div>
310 ??? tip "See Also"
311 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
312 - [`is_in()`][toolbox_python.checkers.is_in]
313 """
314 return value in iterable
317def is_all_values_in_iterable(
318 values: any_collection,
319 iterable: any_collection,
320) -> bool:
321 """
322 !!! summary "Summary"
323 Check if all values in an iterable are present in another iterable.
325 ???+ info "Details"
326 This function is used to verify if all values in a given iterable exist within another iterable.
328 Params:
329 values (any_collection):
330 The iterable containing values to check.
331 iterable (any_collection):
332 The iterable to check within.
334 Returns:
335 (bool):
336 `#!py True` if all values are found in the iterable; `#!py False` otherwise.
338 ???+ example "Examples"
340 Check if all values in an iterable are present in another iterable:
342 ```{.py .python linenums="1" title="Prepare data"}
343 >>> values = [1, 2]
344 >>> iterable = [1, 2, 3]
345 ```
347 ```{.py .python linenums="1" title="Example 1: Check if all values are in the iterable"}
348 >>> is_all_values_in_iterable(values, iterable)
349 ```
350 <div class="result" markdown>
351 ```{.sh .shell title="Output"}
352 True
353 ```
354 !!! success "Conclusion: All values are in the iterable."
356 </div>
358 ```{.py .python linenums="1" title="Example 2: Check if all values are not in the iterable"}
359 >>> is_all_values_in_iterable([1, 4], iterable)
360 ```
361 <div class="result" markdown>
362 ```{.sh .shell title="Output"}
363 False
364 ```
365 !!! failure "Conclusion: Not all values are in the iterable."
367 </div>
369 ??? tip "See Also"
370 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
371 - [`is_all_values_of_type()`][toolbox_python.checkers.is_all_values_of_type]
372 - [`is_in()`][toolbox_python.checkers.is_in]
373 - [`is_all_in()`][toolbox_python.checkers.is_all_in]
374 """
375 return all(value in iterable for value in values)
378def is_any_values_in_iterable(
379 values: any_collection,
380 iterable: any_collection,
381) -> bool:
382 """
383 !!! summary "Summary"
384 Check if any value in an iterable is present in another iterable.
386 ???+ info "Details"
387 This function is used to verify if any value in a given iterable exists within another iterable.
389 Params:
390 values (any_collection):
391 The iterable containing values to check.
392 iterable (any_collection):
393 The iterable to check within.
395 Returns:
396 (bool):
397 `#!py True` if any value is found in the iterable; `#!py False` otherwise.
399 ???+ example "Examples"
401 Check if any value in an iterable is present in another iterable:
403 ```{.py .python linenums="1" title="Prepare data"}
404 >>> values = [1, 4]
405 >>> iterable = [1, 2, 3]
406 ```
408 ```{.py .python linenums="1" title="Example 1: Check if any value is in the iterable"}
409 >>> is_any_values_in_iterable(values, iterable)
410 ```
411 <div class="result" markdown>
412 ```{.sh .shell title="Output"}
413 True
414 ```
415 !!! success "Conclusion: At least one value is in the iterable."
417 </div>
419 ```{.py .python linenums="1" title="Example 2: Check if any value is not in the iterable"}
420 >>> is_any_values_in_iterable([4, 5], iterable)
421 ```
422 <div class="result" markdown>
423 ```{.sh .shell title="Output"}
424 False
425 ```
426 !!! failure "Conclusion: None of the values are in the iterable."
428 </div>
430 ??? tip "See Also"
431 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
432 - [`is_any_values_of_type()`][toolbox_python.checkers.is_any_values_of_type]
433 - [`is_in()`][toolbox_python.checkers.is_in]
434 - [`is_any_in()`][toolbox_python.checkers.is_any_in]
435 """
436 return any(value in iterable for value in values)
439### Aliases ----
440is_type = is_value_of_type
441is_all_type = is_all_values_of_type
442is_any_type = is_any_values_of_type
443is_in = is_value_in_iterable
444is_any_in = is_any_values_in_iterable
445is_all_in = is_all_values_in_iterable
448## --------------------------------------------------------------------------- #
449## `assert_*()` functions ####
450## --------------------------------------------------------------------------- #
453def assert_value_of_type(
454 value: Any,
455 check_type: Union[type, tuple[type, ...]],
456) -> None:
457 """
458 !!! summary "Summary"
459 Assert that a given value is of a specified type or types.
461 ???+ info "Details"
462 This function is used to assert that a given value matches a specified type or any of the types in a tuple of types. If the value does not match the specified type(s), a `#!py TypeError` is raised.
464 Params:
465 value (Any):
466 The value to check.
467 check_type (Union[type, tuple[type]]):
468 The type or tuple of types to check against.
470 Raises:
471 (TypeError):
472 If the value is not of the specified type or one of the specified types.
474 ???+ example "Examples"
476 Assert that a value is of a specific type:
478 ```{.py .python linenums="1" title="Prepare data"}
479 >>> value = 42
480 >>> check_type = int
481 ```
483 ```{.py .python linenums="1" title="Example 1: Assert that value is of type int"}
484 >>> assert_value_of_type(value, check_type)
485 ```
486 <div class="result" markdown>
487 ```{.sh .shell title="Output"}
488 (no output, no exception raised)
489 ```
490 !!! success "Conclusion: The value is of type `#!py int`."
492 </div>
494 ```{.py .python linenums="1" title="Example 2: Assert that value is of type str"}
495 >>> assert_value_of_type(value, str)
496 ```
497 <div class="result" markdown>
498 ```{.sh .shell title="Output"}
499 Traceback (most recent call last):
500 ...
501 TypeError: Value '42' is not correct type: 'int'. Must be: 'str'
502 ```
503 !!! failure "Conclusion: The value is not of type `#!py str`."
505 </div>
507 ```{.py .python linenums="1" title="Example 3: Assert that value is of type int or float"}
508 >>> assert_value_of_type(value, (int, float))
509 ```
510 <div class="result" markdown>
511 ```{.sh .shell title="Output"}
512 (no output, no exception raised)
513 ```
514 !!! success "Conclusion: The value is of type `#!py int` or `#!py float`."
516 </div>
518 ```{.py .python linenums="1" title="Example 4: Assert that value is of type str or dict"}
519 >>> assert_value_of_type(value, (str, dict))
520 ```
521 <div class="result" markdown>
522 ```{.sh .shell title="Output"}
523 Traceback (most recent call last):
524 ...
525 TypeError: Value '42' is not correct type: 'int'. Must be: 'str' or 'dict'.
526 ```
527 !!! failure "Conclusion: The value is not of type `#!py str` or `#!py dict`."
529 </div>
531 ??? tip "See Also"
532 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
533 - [`is_type()`][toolbox_python.checkers.is_type]
534 """
535 if not is_type(value=value, check_type=check_type):
536 msg: str = f"Value '{value}' is not correct type: '{type(value).__name__}'. "
537 if isinstance(check_type, type):
538 msg += f"Must be: '{check_type.__name__}'."
539 else:
540 msg += f"Must be: '{' or '.join([typ.__name__ for typ in check_type])}'."
541 raise TypeError(msg)
544def assert_all_values_of_type(
545 values: any_collection,
546 check_type: Union[type, tuple[type, ...]],
547) -> None:
548 """
549 !!! summary "Summary"
550 Assert that all values in an iterable are of a specified type or types.
552 ???+ info "Details"
553 This function is used to assert that all values in a given iterable match a specified type or any of the types in a tuple of types. If any value does not match the specified type(s), a `#!py TypeError` is raised.
555 Params:
556 values (any_collection):
557 The iterable containing values to check.
558 check_type (Union[type, tuple[type]]):
559 The type or tuple of types to check against.
561 Raises:
562 (TypeError):
563 If any value is not of the specified type or one of the specified types.
565 ???+ example "Examples"
567 Assert that all values in an iterable are of a specific type:
569 ```{.py .python linenums="1" title="Prepare data"}
570 >>> values = [1, 2, 3]
571 >>> check_type = int
572 ```
574 ```{.py .python linenums="1" title="Example 1: Assert that all values are of type int"}
575 >>> assert_all_values_of_type(values, check_type)
576 ```
577 <div class="result" markdown>
578 ```{.sh .shell title="Output"}
579 (no output, no exception raised)
580 ```
581 !!! success "Conclusion: All values are of type `#!py int`."
583 </div>
585 ```{.py .python linenums="1" title="Example 2: Assert that all values are of type str"}
586 >>> assert_all_values_of_type(values, str)
587 ```
588 <div class="result" markdown>
589 ```{.sh .shell title="Output"}
590 Traceback (most recent call last):
591 ...
592 TypeError: Some elements [1, 2, 3] have the incorrect type ['int', 'int', 'int']. Must be 'str'
593 ```
594 !!! failure "Conclusion: Not all values are of type `#!py str`."
596 </div>
598 ```{.py .python linenums="1" title="Example 3: Assert that all values are of type int or float"}
599 >>> assert_all_values_of_type(values, (int, float))
600 ```
601 <div class="result" markdown>
602 ```{.sh .shell title="Output"}
603 (no output, no exception raised)
604 ```
605 !!! success "Conclusion: All values are of type `#!py int` or `#!py float`."
607 </div>
609 ```{.py .python linenums="1" title="Example 4: Assert that all values are of type str or dict"}
610 >>> assert_all_values_of_type(values, (str, dict))
611 ```
612 <div class="result" markdown>
613 ```{.sh .shell title="Output"}
614 Traceback (most recent call last):
615 ...
616 TypeError: Some elements [1, 2, 3] have the incorrect type ['int', 'int', 'int']. Must be: 'str' or 'dict'
617 ```
618 !!! failure "Conclusion: Not all values are of type `#!py str` or `#!py dict`."
620 </div>
622 ??? tip "See Also"
623 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
624 - [`is_all_values_of_type()`][toolbox_python.checkers.is_all_values_of_type]
625 - [`is_type()`][toolbox_python.checkers.is_type]
626 - [`is_all_type()`][toolbox_python.checkers.is_all_type]
627 """
628 if not is_all_type(values=values, check_type=check_type):
629 invalid_values = [value for value in values if not is_type(value, check_type)]
630 invalid_types = [
631 f"'{type(value).__name__}'"
632 for value in values
633 if not is_type(value, check_type)
634 ]
635 msg: str = (
636 f"Some elements {invalid_values} have the incorrect type {invalid_types}. "
637 )
638 if isinstance(check_type, type):
639 msg += f"Must be '{check_type}'"
640 else:
641 types: list[str] = [f"'{typ.__name__}'" for typ in check_type]
642 msg += f"Must be: {' or '.join(types)}"
643 raise TypeError(msg)
646def assert_any_values_of_type(
647 values: any_collection,
648 check_type: Union[type, tuple[type, ...]],
649) -> None:
650 """
651 !!! summary "Summary"
652 Assert that any value in an iterable is of a specified type or types.
654 ???+ info "Details"
655 This function is used to assert that at least one value in a given iterable matches a specified type or any of the types in a tuple of types. If none of the values match the specified type(s), a `#!py TypeError` is raised.
657 Params:
658 values (any_collection):
659 The iterable containing values to check.
660 check_type (Union[type, tuple[type]]):
661 The type or tuple of types to check against.
663 Raises:
664 (TypeError):
665 If none of the values are of the specified type or one of the specified types.
667 ???+ example "Examples"
669 Assert that any value in an iterable is of a specific type:
671 ```{.py .python linenums="1" title="Prepare data"}
672 >>> values = [1, 'a', 3.0]
673 >>> check_type = str
674 ```
676 ```{.py .python linenums="1" title="Example 1: Assert that any value is of type str"}
677 >>> assert_any_values_of_type(values, check_type)
678 ```
679 <div class="result" markdown>
680 ```{.sh .shell title="Output"}
681 (no output, no exception raised)
682 ```
683 !!! success "Conclusion: At least one value is of type `#!py str`."
685 </div>
687 ```{.py .python linenums="1" title="Example 2: Assert that any value is of type dict"}
688 >>> assert_any_values_of_type(values, dict)
689 ```
690 <div class="result" markdown>
691 ```{.sh .shell title="Output"}
692 Traceback (most recent call last):
693 ...
694 TypeError: None of the elements in [1, 'a', 3.0] have the correct type. Must be: 'dict'
695 ```
696 !!! failure "Conclusion: None of the values are of type `#!py dict`."
698 </div>
700 ```{.py .python linenums="1" title="Example 3: Assert that any value is of type int or float"}
701 >>> assert_any_values_of_type(values, (int, float))
702 ```
703 <div class="result" markdown>
704 ```{.sh .shell title="Output"}
705 (no output, no exception raised)
706 ```
707 !!! success "Conclusion: At least one value is of type `#!py int` or `#!py float`."
709 </div>
711 ```{.py .python linenums="1" title="Example 4: Assert that any value is of type dict or list"}
712 >>> assert_any_values_of_type(values, (dict, list))
713 ```
714 <div class="result" markdown>
715 ```{.sh .shell title="Output"}
716 Traceback (most recent call last):
717 ...
718 TypeError: None of the elements in [1, 'a', 3.0] have the correct type. Must be: 'dict' or 'list'
719 ```
720 !!! failure "Conclusion: None of the values are of type `#!py dict` or `#!py list`."
722 </div>
724 ??? tip "See Also"
725 - [`is_value_of_type()`][toolbox_python.checkers.is_value_of_type]
726 - [`is_any_values_of_type()`][toolbox_python.checkers.is_any_values_of_type]
727 - [`is_type()`][toolbox_python.checkers.is_type]
728 - [`is_any_type()`][toolbox_python.checkers.is_any_type]
729 """
730 if not is_any_type(values=values, check_type=check_type):
731 invalid_values = [value for value in values if not is_type(value, check_type)]
732 msg: str = f"None of the elements in {invalid_values} have the correct type. "
733 if isinstance(check_type, type):
734 msg += f"Must be: '{check_type.__name__}'"
735 else:
736 types: list[str] = [f"'{typ.__name__}'" for typ in check_type]
737 msg += f"Must be: {' or '.join(types)}"
738 raise TypeError(msg)
741def assert_value_in_iterable(
742 value: scalar,
743 iterable: any_collection,
744) -> None:
745 """
746 !!! summary "Summary"
747 Assert that a given value is present in an iterable.
749 ???+ info "Details"
750 This function is used to assert that a given value exists within an iterable such as a `#!py list`, `#!py tuple`, or `#!py set`. If the value is not found in the iterable, a `#!py LookupError` is raised.
752 Params:
753 value (scalar):
754 The value to check.
755 iterable (any_collection):
756 The iterable to check within.
758 Raises:
759 (LookupError):
760 If the value is not found in the iterable.
762 ???+ example "Examples"
764 Assert that a value is in an iterable:
766 ```{.py .python linenums="1" title="Prepare data"}
767 >>> value = 2
768 >>> iterable = [1, 2, 3]
769 ```
771 ```{.py .python linenums="1" title="Example 1: Assert that value is in the iterable"}
772 >>> assert_value_in_iterable(value, iterable)
773 ```
774 <div class="result" markdown>
775 ```{.sh .shell title="Output"}
776 (no output, no exception raised)
777 ```
778 !!! success "Conclusion: The value is in the iterable."
780 </div>
782 ```{.py .python linenums="1" title="Example 2: Assert that value is not in the iterable"}
783 >>> assert_value_in_iterable(4, iterable)
784 ```
785 <div class="result" markdown>
786 ```{.sh .shell title="Output"}
787 Traceback (most recent call last):
788 ...
789 LookupError: Value '4' not found in iterable: [1, 2, 3]
790 ```
791 !!! failure "Conclusion: The value is not in the iterable."
793 </div>
795 ??? tip "See Also"
796 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
797 - [`is_in()`][toolbox_python.checkers.is_in]
798 """
799 if not is_in(value=value, iterable=iterable):
800 raise LookupError(f"Value '{value}' not found in iterable: {iterable}")
803def assert_any_values_in_iterable(
804 values: any_collection,
805 iterable: any_collection,
806) -> None:
807 """
808 !!! summary "Summary"
809 Assert that any value in an iterable is present in another iterable.
811 ???+ info "Details"
812 This function is used to assert that at least one value in a given iterable exists within another iterable. If none of the values are found in the iterable, a `#!py LookupError` is raised.
814 Params:
815 values (any_collection):
816 The iterable containing values to check.
817 iterable (any_collection):
818 The iterable to check within.
820 Raises:
821 (LookupError):
822 If none of the values are found in the iterable.
824 ???+ example "Examples"
826 Assert that any value in an iterable is present in another iterable:
828 ```{.py .python linenums="1" title="Prepare data"}
829 >>> values = [1, 4]
830 >>> iterable = [1, 2, 3]
831 ```
833 ```{.py .python linenums="1" title="Example 1: Assert that any value is in the iterable"}
834 >>> assert_any_values_in_iterable(values, iterable)
835 ```
836 <div class="result" markdown>
837 ```{.sh .shell title="Output"}
838 (no output, no exception raised)
839 ```
840 !!! success "Conclusion: At least one value is in the iterable."
842 </div>
844 ```{.py .python linenums="1" title="Example 2: Assert that any value is not in the iterable"}
845 >>> assert_any_values_in_iterable([4, 5], iterable)
846 ```
847 <div class="result" markdown>
848 ```{.sh .shell title="Output"}
849 Traceback (most recent call last):
850 ...
851 LookupError: None of the values in [4, 5] can be found in [1, 2, 3]
852 ```
853 !!! failure "Conclusion: None of the values are in the iterable."
855 </div>
857 ??? tip "See Also"
858 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
859 - [`is_any_values_of_type()`][toolbox_python.checkers.is_any_values_of_type]
860 - [`is_in()`][toolbox_python.checkers.is_in]
861 - [`is_any_in()`][toolbox_python.checkers.is_any_in]
862 """
863 if not is_any_in(values=values, iterable=iterable):
864 raise LookupError(f"None of the values in {values} can be found in {iterable}")
867def assert_all_values_in_iterable(
868 values: any_collection,
869 iterable: any_collection,
870) -> None:
871 """
872 !!! summary "Summary"
873 Assert that all values in an iterable are present in another iterable.
875 ???+ info "Details"
876 This function is used to assert that all values in a given iterable exist within another iterable. If any value is not found in the iterable, a `#!py LookupError` is raised.
878 Params:
879 values (any_collection):
880 The iterable containing values to check.
881 iterable (any_collection):
882 The iterable to check within.
884 Raises:
885 (LookupError):
886 If any value is not found in the iterable.
888 ???+ example "Examples"
890 Assert that all values in an iterable are present in another iterable:
892 ```{.py .python linenums="1" title="Prepare data"}
893 >>> values = [1, 2]
894 >>> iterable = [1, 2, 3]
895 ```
897 ```{.py .python linenums="1" title="Example 1: Assert that all values are in the iterable"}
898 >>> assert_all_values_in_iterable(values, iterable)
899 ```
900 <div class="result" markdown>
901 ```{.sh .shell title="Output"}
902 (no output, no exception raised)
903 ```
904 !!! success "Conclusion: All values are in the iterable."
906 </div>
908 ```{.py .python linenums="1" title="Example 2: Assert that all values are not in the iterable"}
909 >>> assert_all_values_in_iterable([1, 4], iterable)
910 ```
911 <div class="result" markdown>
912 ```{.sh .shell title="Output"}
913 Traceback (most recent call last):
914 ...
915 LookupError: Some values [4] are missing from [1, 2, 3]
916 ```
917 !!! failure "Conclusion: Not all values are in the iterable."
919 </div>
921 ??? tip "See Also"
922 - [`is_value_in_iterable()`][toolbox_python.checkers.is_value_in_iterable]
923 - [`is_all_values_of_type()`][toolbox_python.checkers.is_all_values_of_type]
924 - [`is_in()`][toolbox_python.checkers.is_in]
925 - [`is_all_in()`][toolbox_python.checkers.is_all_in]
926 """
927 if not is_all_in(values=values, iterable=iterable):
928 missing_values = [value for value in values if not is_in(value, iterable)]
929 raise LookupError(f"Some values {missing_values} are missing from {iterable}")
932### Aliases ----
933assert_type = assert_value_of_type
934assert_all_type = assert_all_values_of_type
935assert_any_type = assert_any_values_of_type
936assert_in = assert_value_in_iterable
937assert_any_in = assert_any_values_in_iterable
938assert_all_in = assert_all_values_in_iterable
941## --------------------------------------------------------------------------- #
942## `*_contains()` functions ####
943## --------------------------------------------------------------------------- #
946@typechecked
947def any_element_contains(
948 iterable: str_collection,
949 check: str,
950) -> bool:
951 """
952 !!! note "Summary"
953 Check to see if any element in a given iterable contains a given string value.
954 !!! warning "Note: This check _is_ case sensitive."
956 ???+ abstract "Details"
957 This function is helpful for doing a quick check to see if any element in a `#!py list` contains a given `#!py str` value. For example, checking if any column header contains a specific string value.
959 Params:
960 iterable (str_collection):
961 The iterables to check within. Because this function uses an `#!py in` operation to check if `check` string exists in the elements of `iterable`, therefore all elements of `iterable` must be `#!py str` type.
962 check (str):
963 The string value to check exists in any of the elements in `iterable`.
965 Raises:
966 TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
968 Returns:
969 (bool):
970 `#!py True` if at least one element in `iterable` contains `check` string; `#!py False` if no elements contain `check`.
972 ???+ example "Examples"
974 Check if any element in an iterable contains a specific string:
976 ```{.py .python linenums="1" title="Prepare data"}
977 >>> iterable = ["apple", "banana", "cherry"]
978 >>> check = "an"
979 ```
981 ```{.py .python linenums="1" title="Example 1: Check if any element contains 'an'"}
982 >>> any_element_contains(iterable, check)
983 ```
984 <div class="result" markdown>
985 ```{.sh .shell title="Output"}
986 True
987 ```
988 !!! success "Conclusion: At least one element contains `'an'`."
990 </div>
992 ```{.py .python linenums="1" title="Example 2: Check if any element contains 'xy'"}
993 >>> any_element_contains(iterable, "xy")
994 ```
995 <div class="result" markdown>
996 ```{.sh .shell title="Output"}
997 False
998 ```
999 !!! failure "Conclusion: No elements contain `'xy'`."
1001 </div>
1002 """
1003 return any(check in elem for elem in iterable)
1006@typechecked
1007def all_elements_contains(iterable: str_collection, check: str) -> bool:
1008 """
1009 !!! note "Summary"
1010 Check to see if all elements in a given iterable contains a given string value.
1011 !!! warning "Note: This check _is_ case sensitive."
1013 ???+ abstract "Details"
1014 This function is helpful for doing a quick check to see if all element in a `#!py list` contains a given `#!py str` value. For example, checking if all columns in a DataFrame contains a specific string value.
1016 Params:
1017 iterable (str_collection):
1018 The iterables to check within. Because this function uses an `#!py in` operation to check if `check` string exists in the elements of `iterable`, therefore all elements of `iterable` must be `#!py str` type.
1019 check (str):
1020 The string value to check exists in any of the elements in `iterable`.
1022 Raises:
1023 TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
1025 Returns:
1026 (bool):
1027 `#!py True` if all elements in `iterable` contains `check` string; `#!py False` otherwise.
1029 ???+ example "Examples"
1031 Check if all elements in an iterable contain a specific string:
1033 ```{.py .python linenums="1" title="Prepare data"}
1034 >>> iterable = ["apple", "banana", "peach"]
1035 >>> check = "a"
1036 ```
1038 ```{.py .python linenums="1" title="Example 1: Check if all elements contain 'a'"}
1039 >>> all_elements_contains(iterable, check)
1040 ```
1041 <div class="result" markdown>
1042 ```{.sh .shell title="Output"}
1043 True
1044 ```
1045 !!! success "Conclusion: All elements contain `'a'`."
1047 </div>
1049 ```{.py .python linenums="1" title="Example 2: Check if all elements contain 'e'"}
1050 >>> all_elements_contains(iterable, "e")
1051 ```
1052 <div class="result" markdown>
1053 ```{.sh .shell title="Output"}
1054 False
1055 ```
1056 !!! failure "Conclusion: Not all elements contain `'e'`."
1058 </div>
1059 """
1060 return all(check in elem for elem in iterable)
1063@typechecked
1064def get_elements_containing(iterable: str_collection, check: str) -> tuple[str, ...]:
1065 """
1066 !!! note "Summary"
1067 Extract all elements in a given iterable which contains a given string value.
1068 !!! warning "Note: This check _is_ case sensitive."
1070 Params:
1071 iterable (str_collection):
1072 The iterables to check within. Because this function uses an `#!py in` operation to check if `check` string exists in the elements of `iterable`, therefore all elements of `iterable` must be `#!py str` type.
1073 check (str):
1074 The string value to check exists in any of the elements in `iterable`.
1076 Raises:
1077 TypeError: If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
1079 Returns:
1080 (tuple):
1081 A `#!py tuple` containing all the string elements from `iterable` which contains the `check` string.
1083 ???+ example "Examples"
1085 Extract elements in an iterable that contain a specific string:
1087 ```{.py .python linenums="1" title="Prepare data"}
1088 >>> iterable = ["apple", "banana", "cherry"]
1089 >>> check = "an"
1090 ```
1092 ```{.py .python linenums="1" title="Example 1: Extract elements containing 'an'"}
1093 >>> get_elements_containing(iterable, check)
1094 ```
1095 <div class="result" markdown>
1096 ```{.sh .shell title="Output"}
1097 ('banana',)
1098 ```
1099 !!! success "Conclusion: The element(s) containing `'an'` are extracted."
1101 </div>
1103 ```{.py .python linenums="1" title="Example 2: Extract elements containing 'xy'"}
1104 >>> get_elements_containing(iterable, "xy")
1105 ```
1106 <div class="result" markdown>
1107 ```{.sh .shell title="Output"}
1108 ()
1109 ```
1110 !!! failure "Conclusion: No elements contain `'xy'`."
1112 </div>
1113 """
1114 return tuple(elem for elem in iterable if check in elem)