Use a generator expressions and raise exception if failing

Seems to be the most popular search alternative:
 https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search

Raising StopIteration if not found is better than returning None
to detect such an internal error more easily.
This commit is contained in:
KV 2020-11-27 22:20:45 +01:00
parent f13f8a7dd7
commit 96d393dfb7

View File

@ -116,12 +116,10 @@ def generate_bom(harness):
return [{**entry, 'id': index} for index, entry in enumerate(bom, 1)] return [{**entry, 'id': index} for index, entry in enumerate(bom, 1)]
def get_bom_index(bom: List[dict], extra: AdditionalComponent) -> int: def get_bom_index(bom: List[dict], extra: AdditionalComponent) -> int:
"""Return id of BOM entry or raise StopIteration if not found."""
# Remove linebreaks and clean whitespace of values in search # Remove linebreaks and clean whitespace of values in search
target = tuple(clean_whitespace(v) for v in bom_types_group({**asdict(extra), 'item': extra.description})) target = tuple(clean_whitespace(v) for v in bom_types_group({**asdict(extra), 'item': extra.description}))
for entry in bom: return next(entry['id'] for entry in bom if bom_types_group(entry) == target)
if bom_types_group(entry) == target:
return entry['id']
return None
def bom_list(bom): def bom_list(bom):
keys = ['id', 'item', 'qty', 'unit', 'designators'] # these BOM columns will always be included keys = ['id', 'item', 'qty', 'unit', 'designators'] # these BOM columns will always be included