Sub topic 14
Sharing code as files and Python modules
This chapter assumes you can run a notebook cell, you have a Git folder cloned in your workspace, and you know basic Python imports. It covers how to move reusable logic out of notebooks and into plain files that notebooks import.
Why use files instead of notebooks
%run and dbutils.notebook.run share code between notebooks, but both have limits. %run copies the child's variables into the caller's namespace, which makes dependencies hard to see. Notebooks also can't be unit tested with standard tools, and they diff poorly in code review.
A Python file in a Git folder avoids these problems. It is a normal module you can import, test, lint, and review. The notebook stays thin and calls functions from the module.
| Approach | Shares via | Testable outside Databricks | Namespace effect |
|---|---|---|---|
| `%run ./shared_setup` | Inline execution | No | Pollutes the caller's globals |
| `dbutils.notebook.run` | Separate run, string result | No | None, only a returned string |
| `import mypkg.module` | Python import | Yes | Explicit names only |
A layout that works
Keep notebooks and reusable code in separate folders in the repository.
orders-pipeline/
notebooks/
clean_orders.py
src/
orders/
__init__.py
cleaning.py
tests/
test_cleaning.py
config/
defaults.jsonHere notebooks/clean_orders.py is stored in the source format from earlier in this tutorial, with the # Databricks notebook source header. Every other .py file is a plain workspace file. Without that header, the file is a file, not a notebook.
Write the module
The module holds pure functions, so you can test them without a cluster.
# src/orders/cleaning.py
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
def clean_orders(df: DataFrame) -> DataFrame:
"""Drop rows without an order id and normalize the status column."""
return (
df.filter(F.col("order_id").isNotNull())
.withColumn("status", F.lower(F.trim(F.col("status"))))
)Make the module importable
Python finds modules by searching the directories in sys.path. On recent Databricks Runtime versions, the notebook's own directory is on the path. For notebooks in a Git folder, the repository root is also added. Because your notebook sits in notebooks/ and your code sits in src/, neither location is on the path by default. Check what your runtime does before you assume:
import sys
for p in sys.path[:6]:
print(p)If src is missing, add it explicitly. Build the path from the notebook's working directory so it works in any user's checkout:
import os
import sys
repo_root = os.path.abspath(os.path.join(os.getcwd(), ".."))
src_path = os.path.join(repo_root, "src")
if src_path not in sys.path:
sys.path.insert(0, src_path)
from orders.cleaning import clean_orders
raw = spark.createDataFrame(
[(1, " NEW "), (None, "lost"), (3, "Shipped")],
"order_id int, status string",
)
display(clean_orders(raw))The notebook's working directory is its own folder. This code relies on that, so .. resolves to the repository root. If your runtime uses a different working directory, os.getcwd() will show it.
Reload edited modules
Python imports a module once per session and caches it. If you edit cleaning.py or run a Git pull, the notebook keeps using the old code. You have two options.
Enable autoreload in the first cell of the notebook:
%load_ext autoreload
%autoreload 2Or restart the Python process, which clears all imports and notebook variables:
dbutils.library.restartPython()Autoreload is convenient while you develop. For jobs, don't rely on it. A job starts a fresh process, so every run imports the current code.
Read data files that live next to the code
Files in a Git folder can also be read as files. Use paths relative to a known location instead of hard-coded absolute workspace paths, which contain a username.
import json
import os
config_path = os.path.join(os.getcwd(), "..", "config", "defaults.json")
with open(config_path) as f:
defaults = json.load(f)
print(defaults)This reads on the driver. Spark readers such as spark.read.json use a different file system layer. For small configuration, read it with Python and pass the values on. For real datasets, store them in cloud storage or a volume, not in the repository.
Test the module outside the notebook
Because cleaning.py is a normal file, the same repository can hold tests for it.
# tests/test_cleaning.py
from pyspark.sql import SparkSession
from orders.cleaning import clean_orders
def test_drops_null_ids_and_trims_status():
spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame(
[(1, " NEW "), (None, "lost")],
"order_id int, status string",
)
rows = clean_orders(df).collect()
assert len(rows) == 1
assert rows[0]["status"] == "new"Run it from a CI runner or a terminal with pytest, with src on the path (for example PYTHONPATH=src pytest). This is the main benefit of the file layout. Review and tests happen before the code reaches a job.
Common errors
ModuleNotFoundError: No module named 'orders'.srcis not onsys.path, ororders/is in the wrong place. Printsys.pathandos.getcwd()to compare them.- Edits have no effect. The module is cached. Use
%autoreload 2or restart Python. - Import works for you but fails for a teammate or a job. You added a path with a hard-coded user name. Build paths from
os.getcwd()instead. - Importing a notebook. Move the code into a plain
.pyfile. - Missing
__init__.py. Python can import folders without it as namespace packages, but tools such aspytestand linters behave more predictably when each package folder has one. - Code runs on the driver but not on workers. A function used inside a UDF is shipped to executors. If the module is not available there, you get an import error on the worker. Check the runtime documentation for how your version distributes path directories, and test a UDF that uses the module.
Exercise
Your notebook in notebooks/ runs from orders.cleaning import clean_orders and raises ModuleNotFoundError. The file src/orders/cleaning.py exists. Name two checks you would make and one fix.
Show answer
Print sys.path to see whether the src directory is on it, and print os.getcwd() to confirm which directory the notebook runs from. If src is missing, insert it with sys.path.insert(0, os.path.join(os.path.abspath(os.path.join(os.getcwd(), "..")), "src")) before the import. Also check that the file is a plain .py file and not a notebook, since notebooks cannot be imported.
Exercise
You edit cleaning.py and pull the change, but the running notebook still shows the old behavior. Why, and what are two ways to fix it?
Show answer
Python caches imported modules for the life of the session, so the notebook still holds the old version. Run %load_ext autoreload and %autoreload 2 to reload changed modules automatically, or call dbutils.library.restartPython() to start a fresh Python process.