From 742b4f7e8b4b12f41ee9465f0755abe53f45035a Mon Sep 17 00:00:00 2001 From: huyenngn Date: Tue, 18 Jun 2024 10:08:43 +0200 Subject: [PATCH] refactor: Improve readability of port_exchange_collector --- .../collectors/default.py | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/capellambse_context_diagrams/collectors/default.py b/capellambse_context_diagrams/collectors/default.py index c49fbd12..29124c88 100644 --- a/capellambse_context_diagrams/collectors/default.py +++ b/capellambse_context_diagrams/collectors/default.py @@ -28,6 +28,11 @@ None, ] + Filter: t.TypeAlias = cabc.Callable[ + [cabc.Iterable[common.GenericElement]], + cabc.Iterable[common.GenericElement], + ] + STYLECLASS_PREFIX = "__Derived" @@ -263,27 +268,29 @@ def __collect(target): return all_ports +def _extract_edges( + obj: common.ElementList[common.GenericElement], + attribute: str, + filter: Filter, +) -> common.ElementList[common.GenericElement] | list: + return filter(getattr(obj, attribute, [])) + + def port_exchange_collector( ports: t.Iterable[common.GenericElement], - filter: cabc.Callable[ - [cabc.Iterable[common.GenericElement]], - cabc.Iterable[common.GenericElement], - ] = lambda i: i, + filter: Filter = lambda i: i, ) -> dict[str, common.ElementList[fa.AbstractExchange]]: """Collect exchanges from `ports` savely.""" edges: dict[str, common.ElementList[fa.AbstractExchange]] = {} - for i in ports: - try: - if exs := filter(getattr(i, "exchanges")): - edges[i.uuid] = exs - continue - except AttributeError: - pass - try: - if links := filter(getattr(i, "links")): - edges[i.uuid] = links - except AttributeError: - pass + + for port in ports: + if exs := _extract_edges(port, "exchanges", filter): + edges[port.uuid] = exs + continue + + if links := _extract_edges(port, "links", filter): + edges[port.uuid] = links + return edges