pincer.utils.extraction   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 12
dl 0
loc 44
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A GetItem.__getitem__() 0 2 1

1 Function

Rating   Name   Duplication   Size   Complexity  
A get_index() 0 28 2
1
# Copyright Pincer 2021-Present
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
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
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
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