diff --git a/agenda/thespacedevs.py b/agenda/thespacedevs.py index 1eafa68..6ece23c 100644 --- a/agenda/thespacedevs.py +++ b/agenda/thespacedevs.py @@ -84,46 +84,56 @@ launch_providers = { } +def get_nested(data: dict[str, typing.Any], keys: list[str]) -> typing.Any | None: + """ + Safely get a nested value from a dictionary. + + Args: + data (Dict[str, Any]): The dictionary to search. + keys (List[str]): A list of keys for the nested lookup. + + Returns: + Optional[Any]: The retrieved value, or None if any key is missing. + """ + for key in keys: + if data is None or key not in data: + return None + data = data[key] + return data + + def summarize_launch(launch: Launch) -> Summary: """Summarize rocket launch.""" try: launch_provider = launch["launch_service_provider"]["name"] launch_provider_abbrev = launch_providers.get(launch_provider) - launch_provider_type = launch["launch_service_provider"]["type"] except (TypeError, IndexError): launch_provider = None launch_provider_abbrev = None - launch_provider_type = None - - try: - net_precision = launch["net_precision"]["name"] - except (TypeError, IndexError): - net_precision = None + net_precision = typing.cast(str, get_nested(launch, ["net_precision", "name"])) t0_date, t0_time = format_time(launch["net"], net_precision) - orbit = launch["mission"]["orbit"] if launch["mission"] else None - return { - "name": launch["name"], - "status": launch["status"], - "net": launch["net"], + "name": launch.get("name"), + "status": launch.get("status"), + "net": launch.get("net"), "net_precision": net_precision, "t0_date": t0_date, "t0_time": t0_time, - "window_start": launch["window_start"], - "window_end": launch["window_end"], + "window_start": launch.get("window_start"), + "window_end": launch.get("window_end"), "launch_provider": launch_provider, "launch_provider_abbrev": launch_provider_abbrev, - "launch_provider_type": launch_provider_type, + "launch_provider_type": get_nested(launch, ["launch_service_provider", "type"]), "rocket": launch["rocket"]["configuration"]["full_name"], - "mission": launch["mission"], - "mission_name": (launch["mission"]["name"] if launch["mission"] else None), + "mission": launch.get("mission"), + "mission_name": get_nested(launch, ["mission", "name"]), "pad_name": launch["pad"]["name"], "pad_wikipedia_url": launch["pad"]["wiki_url"], "location": launch["pad"]["location"]["name"], "country_code": launch["pad"]["country_code"], - "orbit": orbit, + "orbit": get_nested(launch, ["mission", "orbit"]), }