/pyxy

HTML in Python

Primary LanguagePythonMIT LicenseMIT

pyxy

pyxy logo

HTML in Python

work-in-progress
contributions appreciated


pyxy lets you put HTML directly in Python code. You can think of it as JSX for Python. It builds on the fantastic work of pyxl, which is a similar project predating JSX. Compared to pyxl, it takes a new approach that makes other tools do most of the work:

  • parso provides the tokenization and parsing, using a custom grammar to enable handling XML
  • htpy is used to rebuild markup

Here's a minimal example:

def is_logged_in() -> bool:
    return False

animal_images = ["cat.png", "dog.png", "cow.png"]
status_image = "logged-in.png" if is_logged_in() else "logged-out.png"

def demo():
    return (
        <div>
            <img src={status_image} />
            <ul>
                { <li><img src={image_file} /></li> for image_file in animal_images }
            </ul>
        </div>
    )

print(demo())
<div><img src="logged-out.png"><ul><li><img src="cat.png"></li><li><img src="dog.png"></li><li><img src="cow.png"></li></ul></div>

IDE Support

Tool support

  • ruff - partial support, see #8
  • mypy - not yet supported, see #9
  • pyright - not yet supported, see #11
  • black - not yet supported, see #7

See also

HTML-in-Python Implementations

Using tagged strings

Syntax Support

HTML-in-* Implementations

  • ECMAScript 4 XML (E4X) - The oldest example I can find of XML being embedded in another language (2004!)
  • JSX - A document detailing the motivations for JSX over other alternatives
  • gox - HTML in Go
  • templ - HTML in Go (but templates?)
  • rsx - HTML in Rust
  • syn-rsx - HTML in Rust
  • rstml - HTML in Rust
  • LuaX - HTML in Lua
  • gccx - HTML in C++
  • rux - HTML in Ruby
  • php