From a3e0823701139c4fc4c04c1c5af004f9dc46434c Mon Sep 17 00:00:00 2001 From: A_D Date: Fri, 16 Apr 2021 17:36:53 +0200 Subject: [PATCH] Added utility sparse list index function Frontier sometimes uses dicts as sparse lists, this should work to index them either way. Doctests included do pass. --- companion.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/companion.py b/companion.py index 60f12d4a..181936ab 100644 --- a/companion.py +++ b/companion.py @@ -22,7 +22,7 @@ from email.utils import parsedate # TODO: see https://github.com/EDCD/EDMarketConnector/issues/569 from http.cookiejar import LWPCookieJar # noqa: F401 - No longer needed but retained in case plugins use it from os.path import join -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union +from typing import Mapping, OrderedDict, TYPE_CHECKING, Any, Dict, List, Optional, TypeVar, Union import requests @@ -848,5 +848,35 @@ def ship(data: CAPIData) -> CAPIData: return filter_ship(data['ship']) +V = TypeVar('V') + + +def index_possibly_sparse_list(data: Union[Mapping[str, V], List[V]], key: int) -> V: + """ + Index into a "list" that may or may not be sparseified into a dict. + + :param data: List or Dict to index + :param key: Key to use to index + :raises ValueError: When data is of an unexpected type + :return: The value at the key + + >>> data = {"1": "test"} + >>> index_possibly_sparse_list(data, 1) + 'test' + + >>> data = ["test_list"] + >>> index_possibly_sparse_list(data, 0) + 'test_list' + """ + if isinstance(data, list): + return data[key] + + elif isinstance(data, (dict, OrderedDict)): + return data[str(key)] + + else: + raise ValueError(f'Unexpected data type {type(data)}') + + # singleton session = Session()