1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-04-17 17:42:20 +03:00

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.
This commit is contained in:
A_D 2021-04-16 17:36:53 +02:00
parent 98c946fa31
commit a3e0823701
No known key found for this signature in database
GPG Key ID: 4BE9EB7DF45076C4

View File

@ -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()