import html from typing import ( TypeAlias, Union, Callable, Optional, cast, ) HTML: TypeAlias = Union[tuple, list, Callable[[], str], None, str, int, float] standalones = ['hr', 'br', 'meta'] def _render_document(document: HTML) -> str: if type(document) == tuple: tag, *body = document if body and type(body[0]) == dict: print(body[0]) attributes = ' '.join(f'{a}="{html.escape(b)}"' for a, b in body[0].items()) body = body[1:] start = f'<{tag} {attributes}>' else: start = f'<{tag}>' if tag in standalones: return start else: items = ''.join(_render_document(b) for b in body) return start + f'{items}' elif callable(document): return str(document()) elif type(document) == list: return ''.join(_render_document(e) for e in document) elif document is None: return '' else: # strings, and everything else return html.escape(str(document)) def render_document(document: HTML) -> str: return '\n' + _render_document(document)