from itertools import takewhile, dropwhile from typing import Optional, Any from mwparserfromhell.nodes import Template, Text, Tag from mwparserfromhell.wikicode import Wikicode def optional_set(haystack: dict, key: str, value: Optional[Any]): """Sets the key to value in haystack only if value is not None""" if value is not None: haystack[key] = value def get_sledrun_description(sledrun: Wikicode) -> Optional[str]: """Get description from sledrun""" for v in sledrun.get_sections(levels=[2], matches='Allgemeines', include_headings=False): dw = dropwhile(lambda n: isinstance(n, Template) or (isinstance(n, Text) and not str(n).strip()), v.nodes) tw = takewhile(lambda n: not (isinstance(n, Tag) and str(n) == '*'), dw) result = str(Wikicode(tw)).strip() if result: return result