PyMalloyAuthor and run Malloy models from Python.
Define semantic models, query with DuckDB, and share models and inputs in notebooks or source bundles.
Define semantic models, query with DuckDB, and share models and inputs in notebooks or source bundles.
Malloy defines sources, measures, joins, and queries and compiles them to SQL. DuckDB executes the SQL. Install PyMalloy:
pip install pymalloyimport pymalloy as pm
orders = pm.sql(
"SELECT * FROM (VALUES ('North', 20), ('North', 22), ('South', 30)) t(region, amount)"
)
model = (
pm.draft()
.sources(
orders=orders.measure(
revenue=pm.col("amount").sum().doc("Booked amount in USD.")
)
)
.queries(
by_region=pm.source("orders").pipe(
pm.view().group_by("region").aggregate("revenue").order_by("region")
)
)
)
print(model.text)
with pm.connect() as con:
print(con.model(model).query("by_region").run().to_pylist())The query returns North revenue 42 and South revenue 30 as exact decimal values.
| Your goal | Start here |
|---|---|
| Run your first Python query | Getting started |
| Reuse a model, select queries, or inspect SQL | Run queries from Python |
| Understand drafts, models, and captured evidence | Concepts and boundaries |
| Compose sources, measures, joins, and views | Author a model |
| Change an existing Malloy file | Edit a model |
| Connect files or catalog tables | Data access |
| Bring prepared Python data into a model | Capture Python data |
| Bind typed query parameters | Givens |
| Display and update a notebook widget | Widgets |
| Run Python in a browser notebook | Browser Python |
| Inspect intermediate values in a notebook | Notebook editing |
| Share an executable notebook | Export notebooks |
| Ship Malloy files and copied inputs | Source bundles |
| Diagnose a failure | Troubleshooting |
| Use JavaScript | Node or browser |
| Look up an exact contract | Python API or CLI |