hyperscript
hyperscript is a lightweight Python library for generating HTML, heavily inspired by the JavaScript HyperScript. It is currently at version 0.3.0 and sees releases periodically for fixes and minor enhancements.
Common errors
-
AttributeError: module 'hyperscript' has no attribute 'div'
cause Attempting to import or use specific HTML tag functions (e.g., `div()`, `p()`) directly from the `hyperscript` module.fixThe `hyperscript` library by `vchan` only provides a single factory function, `h`. You must use `h("div", ...)` or `h("p", ...)` instead. Example: `from hyperscript import h; h("div", "Content")`. -
SyntaxError: invalid syntax (for `class` attribute in keyword arguments) or `TypeError: h() got multiple values for argument 'class'`
cause Attempting to pass HTML attributes like `class` as a direct keyword argument named `class` (which is a reserved Python keyword) or providing attributes both via a dictionary and keyword arguments.fixHTML attributes should be passed either in the second argument as a dictionary (e.g., `h("p", {"class": "my-class"})`) or by including class/id selectors directly in the tag string (e.g., `h("p.my-class#my-id", "Text")`).
Warnings
- breaking Version 0.3.0 introduced a breaking change by replacing 'pipe annotations'. Code relying on a previous, likely internal or specific, syntax using 'pipe annotations' for HTML generation will no longer work.
- gotcha Boolean HTML attributes (e.g., `checked`, `selected`) are handled specifically: `True` renders the attribute, `False` omits it entirely, and `None` also renders the attribute (without a value). This can be a source of confusion if `None` is expected to omit the attribute.
Install
-
pip install hyperscript
Imports
- h
from hyperscript import div, p
from hyperscript import h
Quickstart
from hyperscript import h
# Basic element
print(h("p", "Hello world!"))
# Element with class and ID
print(h("div.container#main", h("h1", "Welcome"), h("p", "This is a paragraph.")))
# Element with attributes and style
print(h("a", {"href": "https://www.example.com", "style": {"color": "blue"}}, "Visit Example"))
# Boolean attribute handling
print(h("input", {"type": "checkbox", "checked": True})) # renders checked
print(h("input", {"type": "checkbox", "checked": False})) # omits checked attribute
print(h("input", {"type": "checkbox", "checked": None})) # renders checked (same as True)