Python API
Installation
pip install gridwell # core: parse, validate, render (no runtime dependencies)
pip install 'gridwell[gt]' # + Great Tables emitter (gt_to_ir / gt_to_dict)Requires Python 3.10 or newer. Wheels use the stable ABI (abi3), so one wheel per platform serves every supported Python version.
Parsing
import gridwell
# From IR as a JSON string, a dict, or a Great Tables GT
table = gridwell.Table(json_str)
table = gridwell.Table(ir_dict)
table = gridwell.Table(gt)
# The same, one kind each
table = gridwell.Table.from_json(json_str)
table = gridwell.Table.from_dict(ir_dict)
table = gridwell.Table.from_gt(gt)
table = gridwell.parse_ir(json_str)Anything else is a TypeError.
Showing a Table
For the getting-started table:
>>> table
<gridwell.Table: 2 columns, 2 rows>
>>> print(table) # the table drawn as plain text, as render_ansi(color=False)
┌────────────┬────────────┐
│ Name │ Score │
├────────────┼────────────┤
│ Alice │ 95 │
│ Bob │ 87 │
└────────────┴────────────┘repr() describes the table: its size, row groups, summary rows and title, and whether it’s invalid. In a notebook (Jupyter, VS Code, Quarto) a table shows as HTML. Each display gets an id of its own (table_id), so the styles of several tables in one notebook stay apart, and is marked so Quarto doesn’t add Bootstrap’s table styling. An invalid table shows its repr, and print() lists its validation errors.
Validation
errors = table.validate() # returns list[str]
if errors:
for e in errors:
print(f"Error: {e}")A valid table can still use a feature a format can’t express. table.warnings(format) lists those warnings for one format, or every format with no argument; it raises like render for invalid IR or an unknown format. A table of a newer minor IR version is warned for first, then what this gridwell leaves out of the table (IGNORED_VALUE, IGNORED_SELECTOR), and parsing a newer minor version gives a UserWarning too.
for w in table.warnings("latex"): # returns list[str]
print(w)Text Rendering
html = table.render_html()
latex = table.render_latex()
typst = table.render_typst()
rtf = table.render_rtf()
svg = table.render_svg()
ansi = table.render_ansi()
pandoc = table.render_pandoc()
quarto = table.render_quarto()
# Generic by name
output = table.render("html")
# Writer options: a dict, or keyword arguments to the per-format methods
output = table.render("html", {"inline_styles": True})
output = table.render_html(inline_styles=True)
# Every format, with its options and defaults, and whether it is experimental
gridwell.formats()See Writer Options for each format’s options.
Binary Rendering
docx_bytes = table.render_docx() # returns bytes
xlsx_bytes = table.render_xlsx()
pptx_bytes = table.render_pptx()
# Generic by name
data = table.render_binary("docx")Saving to a File
Table.save(path, format=None, **options) renders and writes in one call, for every format. The format comes from the file extension (case-insensitive): .html, .tex (latex), .typ (typst), .rtf, .svg, .txt (ansi), .docx, .xlsx, .pptx. .json is both pandoc and quarto, so it needs format. The bytes are written unchanged (UTF-8 text, no added newline). path may be a str or any os.PathLike, and is returned.
from pathlib import Path
table.save("output.docx")
table.save(Path("out") / "table.tex", booktabs=False) # writer options as kwargs
table.save("table.json", format="quarto")
table.save("table.txt") # plain text, no ANSI escapes
table.save("table.txt", color=True) # keep the escapes
table.save("table.html", standalone=True) # a full document, not a fragmentSerialization
json_str = table.to_json()Great Tables Integration
from great_tables import GT, exibble
import gridwell
gt = GT(exibble.head(5))
table = gridwell.Table(gt)
html = table.render_html()
ir_json = gridwell.gt_to_ir(gt) # the IR itselfgt_to_ir() and gt_to_dict() use Great Tables’ own converter, GT.as_gridwell(), once the installed Great Tables has one, and gridwell’s copy until then; pass emitter="upstream" or emitter="gridwell" to choose. See Great Tables Integration.
Conformance
gridwell.conformance checks a table’s IR against an expected table, for an emitter’s tests. Tables are compared as normalized grids, so style ids, key order and how styles are written don’t matter; the check goes by tiers (L0 valid, L1 structure, L2 content, L3 styling), each including the ones before. The expected grids for the conformance cases are in the repository’s conformance/ directory (see its README).
from great_tables import GT, exibble
from gridwell.conformance import assert_conforms, check, normalize
gt = GT(exibble) # the exibble_basic case
grid = normalize(gt, "L1") # a table's grid, as a dict
report = check(gt, grid) # or the path of a grid file, or JSON
report.passed # True
report.tiers # {"L0": "pass", "L1": "pass", "L2": "not checked", "L3": "not checked"}
report.differences # (Difference(tier, path, expected, actual), ...)
print(report)
assert_conforms(gt, "conformance/expected/great_tables/exibble_basic.json")check() takes IR as a JSON string or a dict, a Table, or a GT; IR that doesn’t parse or validate fails L0. Where a grid has nothing at all, a difference’s expected or actual is MISSING (not None, which is a null there). assert_conforms() raises AssertionError with the report when the table doesn’t pass.
Error Handling
ValueError is raised for parse errors (and TypeError for something Table() can’t take), unknown format names, and render failures. render() takes text formats and render_binary() binary ones; the other kind is a ValueError. Invalid writer options raise gridwell.InvalidOptionsError (a subclass of ValueError) naming the problem, e.g. an unknown option. save() raises ValueError for an extension it can’t infer a format from and OSError if the file can’t be written; nothing is written if rendering fails.
Every render_* method validates the table first. If the IR is invalid it raises gridwell.InvalidTableError (a subclass of ValueError) whose message lists the validation errors, e.g. [SPAN_OVERFLOW_RIGHT] Cell at tbody group 0 (row=1, col=3) .... Use table.validate() to get the errors as a list without raising.
try:
table = gridwell.Table.from_json(bad_json)
except ValueError as e:
print(f"Parse error: {e}")
try:
html = table.render_html()
except gridwell.InvalidTableError as e:
print(f"Invalid IR: {e}")Type Checking
The package ships type stubs (py.typed), so mypy, pyright and editors know every signature. Each per-format method takes its options as typed keyword arguments, so a misspelled option or a value of the wrong type is caught before the code runs:
table.render_html(inline_styles=True) # ok
table.render_html(inline_style=True) # error: unexpected keyword argument
table.render_latex(longtable="yes") # error: expected "bool"render() and save() take options of any format, so their options aren’t checked. A path given to save() comes back as the same type (Path in, Path out). For annotations, gridwell._native.FormatInfo is the type of each entry formats() returns; it exists only for type checkers, so import it under TYPE_CHECKING.
Threads
A Table can’t be changed once made, and the work done in Rust runs with the GIL released: parsing JSON, validating, rendering, saving, and repr(), print() and notebook display. Other Python threads run meanwhile, and one table can be rendered on several threads at once, e.g. with concurrent.futures.ThreadPoolExecutor. Serializing a dict to JSON for Table(dict), and converting a Great Tables GT, are Python work and hold it.
from concurrent.futures import ThreadPoolExecutor
jobs = [table.render_html, table.render_latex, table.render_docx]
with ThreadPoolExecutor() as pool:
html, latex, docx = pool.map(lambda render: render(), jobs)