Sub topic 5
Parameterizing a notebook with widgets
This chapter assumes you can write basic Python or SQL, know how to attach a notebook to compute, and know how cells and magic commands work. You'll learn how widgets turn a hard-coded notebook into one that takes inputs.
Why parameterize
A notebook with a literal date or table name in its code works for one run. To reuse it for another day, you have to edit the code, which is error-prone and leaves no record of what was run. A widget is an input control at the top of the notebook. It holds a named value that your code reads. A person can change the value interactively. A job or a calling notebook can supply it without touching the code.
The four widget types
Widgets are created with dbutils.widgets. Every widget has a name, a default value, and an optional label shown in the UI.
| Type | Call | Use it for |
|---|---|---|
| Text | `text(name, default, label)` | Free-form input such as a date or table name |
| Dropdown | `dropdown(name, default, choices, label)` | One value from a fixed list |
| Combobox | `combobox(name, default, choices, label)` | Typing a value, or picking one from a list |
| Multiselect | `multiselect(name, default, choices, label)` | Zero or more values from a fixed list |
dbutils.widgets.text("run_date", "2026-01-01", "Run date")
dbutils.widgets.dropdown("env", "dev", ["dev", "staging", "prod"], "Environment")
dbutils.widgets.multiselect("regions", "eu", ["eu", "us", "apac"], "Regions")
run_date = dbutils.widgets.get("run_date")
env = dbutils.widgets.get("env")
regions = dbutils.widgets.get("regions")
print(f"Processing {run_date} in {env} for {regions}")The widgets appear in a bar at the top of the notebook. Running the cell again does not duplicate them, because creating a widget with an existing name updates its definition.
Values are always strings
dbutils.widgets.get always returns a string. A widget holding 10 gives you "10", and a date widget gives you text, not a date object. Convert explicitly, and do it once near the top of the notebook:
from datetime import date
dbutils.widgets.text("run_date", "2026-01-01", "Run date")
dbutils.widgets.text("batch_size", "1000", "Batch size")
run_date = date.fromisoformat(dbutils.widgets.get("run_date"))
batch_size = int(dbutils.widgets.get("batch_size"))
print(run_date.isoformat(), batch_size + 1)A multiselect returns its selected values as one comma-separated string, such as "eu,us". Split it yourself:
selected = [r for r in dbutils.widgets.get("regions").split(",") if r]The if r filter handles the case where nothing is selected and the string is empty.
Where the value comes from
The notebook sees one current value per widget. That value is resolved in this order:
- A value supplied by the caller, such as a job parameter or an argument to
dbutils.notebook.run. - A value a person typed or picked in the widget bar.
- The default you passed when creating the widget.
This is why the default matters. It is what you get when developing interactively, and it is the fallback when a job omits the parameter. Pick a default that is safe: a test date, a dev environment, never a production table.
Using widget values in SQL
In a %sql cell you can reference widgets without Python. Current runtimes support named parameter markers, written with a colon:
SELECT *
FROM main.sales.orders
WHERE order_date = :run_dateThe marker binds the value as a typed parameter, which avoids SQL injection. It works for values, not for identifiers such as table names. To use a widget as an identifier, wrap it in IDENTIFIER(:table_name).
SELECT count(*) FROM IDENTIFIER(:table_name)Older notebooks use ${run_date} string substitution. It still appears in existing code, but it pastes raw text into the query. Prefer the :name form in new work. Parameter markers need a reasonably recent Databricks Runtime, so check your cluster's version if the syntax fails.
In Python, you can also pass the value through spark.sql using the args argument:
run_date = dbutils.widgets.get("run_date")
df = spark.sql(
"SELECT * FROM main.sales.orders WHERE order_date = :d",
args={"d": run_date},
)
display(df)Managing widgets
dbutils.widgets.getAll()returns a dictionary of every widget and its value. It needs a recent runtime.dbutils.widgets.remove("run_date")deletes one widget.dbutils.widgets.removeAll()deletes all of them.
Removal is useful when you change a widget's definition. A widget keeps its current value across edits. If you change the default in the code but the widget already holds a different value, you will still see the old value. Remove the widget and re-run the cell, and the new default applies.
Common errors
- The widget is not defined. Calling
geton a name that was never created raises an error. This happens when thegetcell runs before the creation cell, or afterremoveAll(). Create all widgets in the first cell, then read them. - The default is not in the choices. For a dropdown, the default must be one of the listed choices. Otherwise creation fails.
- A number used as a number. Code such as
batch_size * 2on a string repeats the text rather than doubling the value. Convert withint()orfloat(). - Stale values after editing the default. As described above, remove and recreate the widget.
- Whitespace and case. A job parameter
" 2026-01-02"is not the same as"2026-01-02". Call.strip()on text inputs, and validate them before use. - Different names between caller and notebook. The caller's key must match the widget name exactly. A key that does not match is silently ignored, and the default is used instead. That can run a job against the wrong date without any error.
Validate early
Because widget text is unconstrained, check it at the top and fail fast with a clear message:
from datetime import date
dbutils.widgets.text("run_date", "2026-01-01", "Run date")
dbutils.widgets.dropdown("env", "dev", ["dev", "staging", "prod"], "Environment")
raw_date = dbutils.widgets.get("run_date").strip()
env = dbutils.widgets.get("env")
try:
run_date = date.fromisoformat(raw_date)
except ValueError:
raise ValueError(f"run_date must be YYYY-MM-DD, got {raw_date!r}")
if env not in ("dev", "staging", "prod"):
raise ValueError(f"Unknown env: {env!r}")
print(f"Running {run_date} against {env}")A run that stops in the first cell is far cheaper than one that writes the wrong partition.
How this connects to the rest of the workflow
The same widget names are the interface other tools use. A parent notebook can pass them with dbutils.notebook.run. A job's notebook task lists them as parameters. Treat widget names as a public contract: renaming one breaks every caller. Keep the set small, document each one in a markdown cell, and give each a safe default.
Exercise
A job passes the parameter run_dat with the value 2026-03-05 to a notebook that defines the text widget run_date with the default 2026-01-01. The job succeeds. Which date does the notebook process, and why? How would you make a mistake like this fail loudly?
Show answer
It processes 2026-01-01. The key run_dat does not match the widget name run_date, so the supplied value is ignored and the default is used. To fail loudly, avoid a real-looking default. Use an empty string as the default, then validate at the top, for example if not raw_date: raise ValueError("run_date is required"). A misspelled key then stops the run in the first cell.
Exercise
You create a multiselect widget regions with choices eu, us, apac and select eu and us. What does dbutils.widgets.get("regions") return, and how do you turn it into a Python list?
Show answer
It returns the string "eu,us". Convert it with [r for r in dbutils.widgets.get("regions").split(",") if r], which gives ["eu", "us"] and an empty list if nothing is selected.