Sub topic 6
Reusing and chaining notebooks
This chapter assumes you can run cells in a Databricks notebook, that you know what a widget is (covered in the previous chapter), and that your notebook is attached to running compute. It covers the two ways to call one notebook from another. They look alike but behave very differently.
Two mechanisms, two execution models
Databricks gives you two ways to reuse a notebook:
%runis a magic command. It pastes the target notebook into the current one, as if its cells were written there.dbutils.notebook.run()is a function call. It starts the target notebook as a separate run and gives you back a string.
The choice depends on what you need back. If you want functions, classes, and variables, use %run. If you want to run a unit of work with parameters and get a status back, use dbutils.notebook.run().
| Aspect | `%run` | `dbutils.notebook.run()` |
|---|---|---|
| Where it runs | Inline, in the caller's session | Separate run, started from the caller |
| Variables and functions | Become available in the caller | Not shared with the caller |
| Parameters | Not the intended use | Passed as a dictionary of strings |
| Return value | None | A string from `dbutils.notebook.exit()` |
| Timeout | None | Required argument |
| Can be called in a loop or conditionally | No, it is a magic command in its own cell | Yes, it is ordinary Python |
| Failure of the child | Cell fails in the caller | Raises an exception you can catch |
Inlining code with %run
Put %run alone in a cell, with a path to the other notebook:
%run ./shared_setupThe cell must contain only this command. Any other code in the same cell is not run as you expect. After the cell succeeds, everything that shared_setup defined is available in later cells of the caller.
A typical shared_setup notebook holds helper functions and configuration:
# In shared_setup
CATALOG = "main"
SCHEMA = "sales"
def full_name(table: str) -> str:
return f"{CATALOG}.{SCHEMA}.{table}"After the %run cell, the caller can call full_name("orders") directly.
Paths starting with ./ or ../ are relative to the calling notebook's own folder. This is why they keep working when you clone a Git folder into a different workspace location. Absolute workspace paths break in that case, so prefer relative ones.
Since the code is inlined, name clashes are a real risk. If the caller and the included notebook both define df, the later definition wins silently. Keep included notebooks to definitions (functions, constants) and avoid top-level data processing in them.
Starting a separate run with dbutils.notebook.run
The function takes three arguments: the notebook path, a timeout in seconds, and a dictionary of arguments.
result = dbutils.notebook.run("./child_notebook", 60, {"run_date": "2026-01-02"})
print(result)The child reads its arguments through widgets. Each key in the dictionary sets the widget with the same name. The child ends by returning a string:
# In child_notebook
run_date = dbutils.widgets.get("run_date")
dbutils.notebook.exit(f"done {run_date}")A few rules follow from how this works:
- Arguments and the return value are strings. Convert numbers and dates on the receiving side.
- A timeout of
0means no timeout. If the child runs longer than the timeout you set, the call fails. - The child must declare the widget (with
dbutils.widgets.text(...)and a default) for the notebook to also run on its own. The caller's argument overrides the default. - The child runs on the same compute as the caller. It does not get its own cluster, so the work still competes for the same resources.
The diagram shows the sequence of a call.
Returning more than one value
Because the return value is a single string, encode structured results as JSON. For large results, write the data to a table and return only its name.
# In child_notebook
import json
run_date = dbutils.widgets.get("run_date")
rows_written = 120
dbutils.notebook.exit(json.dumps({"status": "ok", "run_date": run_date, "rows": rows_written}))# In the parent notebook
import json
raw = dbutils.notebook.run("./child_notebook", 120, {"run_date": "2026-01-02"})
info = json.loads(raw)
print(info["status"], info["rows"])Handling failure and retries
If the child raises an error or exceeds the timeout, dbutils.notebook.run() raises an exception in the parent. Wrap the call to decide what happens next:
import time
def run_with_retry(path, timeout, args, attempts=3):
for attempt in range(1, attempts + 1):
try:
return dbutils.notebook.run(path, timeout, args)
except Exception as error:
print(f"Attempt {attempt} failed: {error}")
if attempt == attempts:
raise
time.sleep(10)
print(run_with_retry("./child_notebook", 120, {"run_date": "2026-01-02"}))The final raise matters. If the parent swallows the error, the whole job reports success even though a step failed.
Running several children at once
Since the call is plain Python, you can run children in parallel with threads. Each call still uses the shared compute, so keep the thread count modest.
from concurrent.futures import ThreadPoolExecutor
dates = ["2026-01-01", "2026-01-02", "2026-01-03"]
def load(date):
return dbutils.notebook.run("./child_notebook", 300, {"run_date": date})
with ThreadPoolExecutor(max_workers=3) as pool:
results = list(pool.map(load, dates))
print(results)Common errors
%runin a cell with other code. Move it into its own cell.- Passing a number or date object as an argument. Pass
str(value)and parse it in the child. - Expecting variables from a child started with
dbutils.notebook.run(). They are not shared. Return a string or write to a table. - Child not found. Check the relative path against the caller's folder, not against your current browser location.
- Timeouts set too low. A cold start of a table scan can exceed 60 seconds. Pick a value from observed run times.
When to use a workflow instead
Chaining with dbutils.notebook.run() puts the control flow in code. For a fixed sequence of steps, a Databricks job with several tasks and dependencies gives you per-task status, retries, and alerts without writing that logic yourself. Notebook-to-notebook calls suit dynamic cases, such as looping over a list that is only known at run time. A later chapter shows jobs reading their notebooks from a Git source.
Exercise
A parent notebook must call a child once for each date in a list, collect each child's row count, and fail the whole run if any child fails. Which mechanism do you use, and how do you get the row count back?
Show answer
Use dbutils.notebook.run() in a loop, because %run cannot be called repeatedly with different arguments and returns nothing. The child passes the row count with dbutils.notebook.exit(str(count)), or as JSON if there are several values, and the parent converts it with int() or json.loads(). Do not catch the exception without re-raising it, so a failing child fails the parent.