HashedSubscriptableType.__getitem__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 5
Ratio 55.56 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 5
loc 9
rs 10
c 0
b 0
f 0
1
from typing import Any
2
3
from typish import SubscriptableType
4
5
6 View Code Duplication
class HashedSubscriptableType(SubscriptableType):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
7
    """
8
    An extension of SubscriptableType that caches the __getitem__ to ensure an
9
    identical result per set of parameters.
10
    """
11
    _cache = {}
12
13
    def __getitem__(cls, item: Any) -> Any:
14
        # Take the item's class name into account to distinguish between
15
        # e.g. ints and floats.
16
        hashed = hash('{}{}{}'.format(
17
            cls.__name__, item.__class__.__name__, item))
18
        if hashed not in cls._cache:
19
            cls._cache[hashed] = SubscriptableType.__getitem__(cls, item)
20
        result = cls._cache[hashed]
21
        return result
22