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
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 |