Skip to content

Commit

Permalink
feat: Add (has|iter)_children methods
Browse files Browse the repository at this point in the history
This can improve performance when one just needs to know, if an item
has children.
  • Loading branch information
jamilraichouni committed Oct 20, 2023
1 parent c843bc2 commit 070e82d
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions capellambse/model/common/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,12 +404,24 @@ def _repr_html_(self) -> str:
def get_children(self) -> MixedElementList:
"""Return all model elements that are children of this one.
The list returned from this method contains all model element
that are direct descendants of this element, with regard to the
XML hierarchy (usually referred to as "owned objects" in the
metamodel).
.... seealso::
:meth:`iter_children`
"""
return MixedElementList(
self._model, [ele._element for ele in self.iter_children()]
)

def has_children(self) -> bool:
return next(self.iter_children(), None) is not None

def iter_children(self) -> t.Iterator[GenericElement]:
"""Yield model elements that are children of this one.
The elements yielded from this generator are the direct
descendants of this element, with regard to the XML hierarchy
(usually referred to as "owned objects" in the metamodel).
"""
elements: list[etree._Element] = []
for attr in dir(self):
if attr.startswith("_"):
continue
Expand All @@ -422,10 +434,9 @@ def get_children(self) -> MixedElementList:
):
if acc.aslist is None:
if getattr(self, attr) is not None:
elements.append(getattr(self, attr)._element)
yield getattr(self, attr)
else:
elements.extend(i._element for i in getattr(self, attr))
return MixedElementList(self._model, elements)
yield from getattr(self, attr)

if t.TYPE_CHECKING:

Expand Down Expand Up @@ -782,7 +793,7 @@ def __html__(self) -> markupsafe.Markup:
return markupsafe.Markup("<p><em>(Empty list)</em></p>")

fragments = ['<ol start="0" style="text-align: left;">']
for i in self:
for i in [i for i in self if i is not None]:
fragments.append(f"<li>{i._short_html_()}</li>")
fragments.append("</ol>")
return markupsafe.Markup("".join(fragments))
Expand Down

0 comments on commit 070e82d

Please sign in to comment.