Skip to content

Instantly share code, notes, and snippets.

@ThePlaneOnGit
Last active September 2, 2026 14:02
Show Gist options
  • Select an option

  • Save ThePlaneOnGit/abd310b9937a6b58c62a921a015019e7 to your computer and use it in GitHub Desktop.

Select an option

Save ThePlaneOnGit/abd310b9937a6b58c62a921a015019e7 to your computer and use it in GitHub Desktop.
A Lib I made For Simpler XML
#!/usr/bin/env python3
__author__ = "Beluga XL"
__copyright__ = "Copyright 2026, Beluga XL"
__credits__ = ["Beluga XL"]
__lisence__ = "LGPLv3"
__version__ = "1.0.0"
__maintainer__ = "Beluga XL"
__email__ = "deplenguy@proton.me"
__status__ = "Prototype"
__date__ = "Fri Aug 28 08:43:16 PM UTC 2026"
__doc__ = """
Library That Allows For A Simpler Usage Of XML Elements
"""
from abc import ABC, ABCMeta, abstractmethod
from typing import Self
class XML(ABC, metaclass=ABCMeta):
"""Abstraction Of XML Element"""
def __init__(self, *children, **properties):
self.children = list(children)
self.properties = properties
@abstractmethod
def __str__(self: Self) -> str:
return NotImplemented
def __len__(self):
return len(self.children)
def append(self, child: Self) -> Self:
self.children.append(child)
return self
def pappend(self, property: tuple[str, str]) -> Self:
self.properties[property[0]] = property[1]
return self
class close_tag(XML):
"""Class Representing a Close Tag"""
name = ""
def __init__(self, *children, **properties):
if len(children) > 0: raise ValueError("This Tag Can Not Have Children")
XML.__init__(self, **properties)
def append(*_):
raise ValueError("This Tag Can Not Have Children")
def __str__(self) -> str:
ret: str = f"<{self.name}"
for (k, v) in self.properties.items():
ret += f" {k}=\"{v}\""
ret += "/>"
return ret
class n_close_tag(XML):
"""Class Representing a Non-close Tag"""
name = ""
def __str__(self) -> str:
ret: str = f"<{self.name}"
for (k, v) in self.properties.items():
ret += f" {k}=\"{v}\""
ret += ">"
for child in self.children:
ret += str(child)
ret += f"</{self.name}>"
return ret
class html(n_close_tag):
"""Special Form Of An XML Element To Represent HTML Tag"""
name = "html"
def __str__(self: Self) -> str:
return "<!DOCTYPE html>" + super().__str__()
def xml_builder(elem_name: str, is_close_only: bool = False):
"""Builder Function for XML Element Classes
Keyword Arguments:
elem_name -- The name of the element
is_close_only -- True for close tags like `<img/>` otherwise False/Unset
Return -- Class representing XML element
"""
class C(close_tag if is_close_only else n_close_tag):
name = elem_name
return C
if __name__ == "__main__":
# Examples Of XML Elements
img = xml_builder("img", True)
h3 = xml_builder("h3")
ul = xml_builder("ul")
li = xml_builder("li")
print(ul(*[li(x) for x in range(20)]), img(src = "Hello"))
print(html(*[h3(f"{y}, {z}") for z in range(20) for y in range(20)]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment