Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created August 31, 2022 23:11
Show Gist options
  • Save kurtbrose/fcbcaac6e7d12c83953401a2a90171ac to your computer and use it in GitHub Desktop.
Save kurtbrose/fcbcaac6e7d12c83953401a2a90171ac to your computer and use it in GitHub Desktop.
python 3 module __getattr__ is neat
from dataclasses import dataclass, field
from typing import Union
@dataclass
class _Tag:
name: str
attributes: dict[str, str] = field(default_factory=dict)
children: tuple[Union["Tag", str]] = ()
def __call__(self, *children, **attributes):
return self.__class__(self.name, {**self.attributes, **attributes}, self.children + children)
def render(self):
tag = "<" + self.name
if self.attributes:
tag += " " + ''.join(f'{key}="{val}"' for key, val in self.attributes.items())
if self.children:
inner = "".join([v if isinstance(v, str) else v.render() for v in self.children])
return f"{tag}>{inner}</{self.name}>"
return f"{tag}/>"
def __getattr__(name):
return _Tag(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment