Python is a batteries included language. So why not use xml.dom.minidom
?
from typing import List
from xml.dom.minidom import getDOMImplementation, Document
def getDOM() -> Document:
impl = getDOMImplementation()
dt = impl.createDocumentType(
"html",
"-//W3C//DTD XHTML 1.0 Strict//EN",
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
)
return impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
def ul(items: List[str]) -> str:
dom = getDOM()
html = dom.documentElement
ul = dom.createElement("ul")
for item in items:
li = dom.createElement("li")
li.appendChild(dom.createTextNode(item))
ul.appendChild(li)
html.appendChild(ul)
return dom.toxml()
if __name__ == "__main__":
print(ul(["first item", "second item", "third item"]))
outputs:
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html>
<ul>
<li>first item</li>
<li>second item</li>
<li>third item</li>
</ul>
</html>
The interface does not look like pythonic, but if you have been a fronted developer and used JavaScript DOM manipulation, it matches your mind better and yes it frees you from adding a needless dependency.
print
-ing HTML. The Dominate library just clicks for me. To me Dominate feels very lisp-y in the sense that you always hear that Lisp is great for using the language itself as a Domain Specific Language. Well, it turns out Python is really good for this as well! – Fleecy