1 | # Copyright Pincer 2021-Present |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
2 | # Full MIT License can be found in `LICENSE` at the project root. |
||
3 | |||
4 | from typing import Any, Optional, Protocol, TypeVar |
||
5 | |||
6 | T = TypeVar("T") |
||
7 | |||
8 | |||
9 | class GetItem(Protocol): |
||
10 | """Represents a class which implements the __getitem__ property.""" |
||
11 | |||
12 | def __getitem__(self, key: int) -> Any: |
||
13 | return ... |
||
14 | |||
15 | |||
16 | def get_index( |
||
17 | collection: GetItem, index: int, fallback: Optional[T] = None |
||
0 ignored issues
–
show
|
|||
18 | ) -> Optional[T]: |
||
19 | """Gets an item from a collection through index. |
||
20 | Allows you to provide a fallback for if that index is out of bounds. |
||
21 | |||
22 | Parameters |
||
23 | ---------- |
||
24 | collection: :class:`~pincer.utils.extraction.GetItem` |
||
25 | The collection from which the item is retrieved. |
||
26 | index: :class:`int` |
||
27 | The index of the item in the collection. |
||
28 | fallback: Optional[T] |
||
29 | The fallback value which will be used if the index doesn't |
||
30 | exist. Default value is None. |
||
31 | |||
32 | Returns |
||
33 | ------- |
||
34 | Optional[T] |
||
35 | The item at the provided index from the collection, or if that |
||
36 | item doesn't exist it will return the fallback value. |
||
37 | """ |
||
38 | |||
39 | try: |
||
40 | return collection[index] |
||
41 | |||
42 | except IndexError: |
||
43 | return fallback |
||
44 |