Python
Python Libraries for Data Engineering: When to Reuse Code, Build Your Own, and Optimize Performance
When to copy notebook code, share a .py module, reference another notebook or build a Python library in Microsoft Fabric, what each option costs in maintenance, deployment and startup, and why a library doesn't make code faster by itself.
On this page
Every data platform has a function that exists in six copies. It started as twenty lines in one notebook: clean the country codes, cast the amounts, rename the columns the way the warehouse expects. Then a second pipeline needed it, and copying was faster than thinking. A year later, four of the copies have a bug fix that the other two don’t, one of them silently drops nulls, and nobody knows which version the finance report uses.
This article is about the decision behind that function. In Microsoft Fabric it comes down to a practical question:
should you copy the code, put it in a reusable .py file, reference another notebook, or build a Python library?
And when should you use someone else’s library instead? It also tackles a claim that comes up in every such
discussion, that a library will make the pipeline faster. Sometimes it does. Often it changes nothing, and occasionally
it makes things slower. The only way to know is to measure, and measuring Spark correctly has traps of its own.
One fictional scenario runs through the article: three Fabric notebooks ingest merchant files and apply the same
normalization and validation rules. You’ll see those rules evolve from repeated notebook code to a shared module and
then to a versioned package. Every code sample in that example was executed and tested locally against PySpark 3.5,
4.1 and 4.3. Nothing needs to be installed beyond PySpark to follow it. Its code appears as plain code blocks,
because it lives in tested .py files; the one notebook shown as a notebook, in section 14, is a real notebook, with
the outputs it produced when it ran.
Two libraries developed alongside this site appear later as larger examples: JaviMapper, which proposes and applies reviewed column mappings, and JaviPerf, an experimental performance diagnostics library. Neither is published to PyPI, and you don’t need either to follow the article. They’re worked examples, not products to adopt.
1. The problem with copying code across pipelines
Copying feels free because its costs arrive later and somewhere else.
- Drift. Each copy evolves on its own. A fix lands in the pipeline where the bug was noticed, and only there.
- Silent inconsistency. Two reports that should agree don’t, because their pipelines clean the same column differently. Nobody notices until a reconciliation fails.
- Untested code. Notebook cells are rarely unit-tested. Six copies means six untested implementations, not one.
- Invisible ownership. When the logic is wrong, there is no single place to fix it and no single person responsible for it.
- Upgrade friction. A runtime upgrade (for example from Fabric Runtime 1.3 to 2.0) has to be validated against every copy separately.
None of this means every repeated line deserves a library. Two pipelines sharing three lines of withColumnRenamed
is not a problem worth an engineering process. The question is when the cost of the copies exceeds the cost of
maintaining one shared version properly.
2. Script, module, package, library, framework
These words are often used interchangeably. The distinctions matter, because each step up adds a boundary you have to maintain.
- FrameworkCalls your code: owns the control flow (Airflow DAGs, pytest, Django)
- LibraryYou call it: a package with a public API, docs, versions and an owner
- PackageAn installable distribution, usually a wheel (.whl) with metadata
- ModuleOne importable .py file; reusable within a project
- Script or notebookRuns top to bottom; reused by copying
- A script or notebook runs from top to bottom. Its reuse mechanism is copy and paste.
- A module is a
.pyfile you canimport. Python’s documentation calls it “a file containing Python definitions and statements”. Modules are the first real reuse step, and they need no packaging. - A package is something you can install. In practice that means a wheel: a built archive with a name, a
version and declared dependencies, which
pipcan install into any environment. - A library is a package plus a promise: a documented public API, a versioning policy, tests, an owner, and a changelog. A wheel without those is just a zip file someone has to reverse-engineer.
- A framework inverts control. You call a library; a framework calls you (a pytest test function, an Airflow task, a Django view). Building a framework is a much bigger commitment than building a library, and data teams rarely need one.
3. Importing code versus running a notebook
Fabric offers two families of reuse, and most confusion comes from mixing them up.
Importing brings functions and classes into your notebook’s Python process. You call them with your data and get a
result back. Where the code comes from (a .py file in the notebook’s resources, a library in an Environment, a
package from PyPI) changes how it’s delivered, not how it behaves. Imported functions can be unit-tested on a laptop.
Running a notebook executes cells that live in another notebook. Fabric has two ways to do it, and they behave differently:
%runexecutes the referenced notebook’s cells in your session. Microsoft’s documentation states that “all the variables defined in the reference notebook are available in the current notebook”. It’s the closest thing Fabric notebooks have toimportfor another notebook, but it’s still code execution: everything in those cells runs, every time.notebookutils.notebook.runstarts a reference run of another notebook. Its documented return value is “the exact string passed tonotebookutils.notebook.exit(value)”. No DataFrame, no functions, no variables come back. That’s orchestration: running a step of a workflow, like a pipeline activity.
- importReuse functions
- Module or package.py file, resources folder, Environment, wheel
- import merchant_rulesNames enter your namespace
- split_valid(raw)Your DataFrame in, DataFrames out
- %runInclude a notebook
- %run nb_merchant_rulesSame workspace only
- Its cells executeIn your session, every time
- Its variables appearFunctions and values join your namespace
- notebook.runOrchestrate a run
- notebookutils.notebook.runName, timeout, arguments
- Separate reference runSnapshot link in the output
- Exit string returnedWhatever the child passed to exit()
import |
%run |
notebookutils.notebook.run |
|
|---|---|---|---|
| What you get back | Functions and classes to call | The referenced notebook’s variables and functions | One string: the child’s exit value |
| Where it runs | Your notebook’s Python process | Your session, inline | A reference run on the caller’s Spark pool |
| Parameters | Function arguments, any Python type | int, float, bool and string only |
An arguments dictionary for the child’s parameter cell |
| Scope | Wherever the code is installed or uploaded | Notebooks in the same workspace | Same workspace, or another one by workspace ID |
| Natural use | Shared logic | Sharing setup or helpers in one workspace | Running notebooks as steps, in sequence or in parallel |
The rest of the article uses this distinction. When you need the same logic in several notebooks, you want something you can import. When you need to run the same process for several inputs, you want orchestration.
4. The reuse options in Microsoft Fabric
Here is every practical option, with where the code lives and how a notebook reaches it. The Fabric behaviour below is taken from Microsoft Learn as of November 2026; the sources are listed at the end.
| Option | Where the code lives | How a notebook uses it | Shared with | In Git |
|---|---|---|---|---|
| Code in the notebook | A cell | Runs in place | That notebook | With the notebook |
| Copied code | A cell in each notebook | Runs in place | Nobody: each copy is separate | Each copy separately |
.py module in a repository |
Your source repository | Delivered by one of the options below | Wherever it’s delivered | Yes |
| Notebook resources | The notebook’s builtin/ folder |
import builtin.<folder>.<module>, or %run -b file.py |
That notebook and its reference runs | Optional, off by default |
Environment custom .py |
An Environment’s custom libraries | Installed with the Environment | Notebooks attached to it | Committed with the Environment |
Environment wheel (.whl) |
An Environment’s custom libraries | import package_name |
Notebooks attached to it | Committed with the Environment |
%run |
Another notebook in the workspace | Its cells run in your session | Notebooks in the same workspace | As a notebook |
notebookutils.notebook.run |
Another notebook | A reference run that returns a string | Callers in any workspace, by ID | As a notebook |
| Third-party library | PyPI, conda or a wheel file | import after installation |
Wherever it’s installed | Listed in the Environment’s YAML |
Code directly in the notebook
The right default for anything used once: exploration, a one-off backfill, logic specific to one source. It’s visible, easy to change and needs no process. Its limit is that it can only be reused by copying.
Copying code between notebooks
Copying is reuse with no shared state. It’s quick, and every notebook stays independent, which is occasionally what you want (two pipelines whose rules are meant to diverge). The costs are the ones in section 1: drift, untested copies and no owner. Copying is a reasonable first step, not a resting place for logic several pipelines depend on.
A reusable .py module in your repository
A module is a .py file of functions with no notebook around it. It’s the first step that makes testing realistic:
pytest can import it and run it against a local Spark session. A module in a Git repository is the source of truth;
Fabric still needs one of the next options to deliver it to a notebook.
Notebook resources
Every Fabric notebook has a built-in resources folder, which Microsoft describes as “a system-defined folder unique to
each notebook”, for small files such as code modules. A notebook reaches it through the relative path builtin/.
Microsoft’s documented import example places a module in a subfolder:
import builtin.localLib.util as util
util.func1()
What to know before relying on it:
- It’s per notebook. Three notebooks that use the same module need three uploads: copying, with extra steps. Files in the folder are also “scoped to the current notebook session”.
- Limits. 500 MB in total, 100 MB per file, and 100 files and folders.
- Git is optional. The folder “can be committed to Git”, but that is “optional and off by default”, with a 50 MB commit limit.
- High concurrency. Microsoft notes that “reading/writing with a relative path is not functioning in a High concurrency session”.
- Reference runs can use these files, but
builtin/“will always point to the root notebook’s built-in folder”.
Environments also have a Resources folder, mounted at /env for Spark notebooks attached to the Environment and
shared by all of them. It’s meant for small files; Microsoft documents that it isn’t currently supported by Git
integration or deployment pipelines, so it’s a poor home for code you need to review and promote.
Fabric Environment custom .py files
An Environment’s Custom libraries accept .whl, .py, .jar and .tar.gz files, and Microsoft’s guidance is to
“use the .whl and .py file format for Python”. A .py file published there is available to every notebook
attached to the Environment, and it’s committed to Git with the Environment.
Two cautions. The pages we checked don’t document the import name of an uploaded .py file, so confirm it with a test
notebook (for example import merchant_rules) before you depend on it. And the general library-management page lists
only .whl, .jar and .tar.gz for custom libraries and recommends .whl for Python. A .py file also carries no
version and no declared dependencies, which matters as soon as two teams depend on it.
Fabric Environment .whl packages
A wheel is the packaged form: a name, a version, declared dependencies and an installable archive. Uploaded to an Environment’s custom libraries and published, it’s installed for every notebook attached to that Environment, or to the whole workspace when it’s the workspace default. The installation section covers the publish modes and their effect on session start.
%run for notebooks and scripts
%run references a notebook by name, optionally with parameters:
%run nb_merchant_rules { "strict_country_codes": true }
It can also run a .py or .sql script from the notebook’s resources folder with the -b (--builtin) flag, as in
%run -b merchant_rules.py. The documented rules:
- Only notebooks in the same workspace can be referenced.
- Parameters support
int,float,boolandstring, and must match the referenced notebook’s parameter cell. - Calls can be nested but not recursive, and a depth greater than five raises an exception.
- In Python notebooks (the single-node, non-Spark experience),
%runreferences only notebooks, not.pymodules from the resources folder.
The Microsoft pages we checked disagree about %run in pipelines: one states that notebook reference “works in both
interactive mode and pipeline”, while the list of magics supported in a pipeline doesn’t include it. Test it in your
own pipeline before relying on it there.
%run is convenient because nothing needs packaging. Its costs follow from how it works: the referenced cells run
every time, their names land in your namespace without an explicit import list, and every caller always gets the
current version of the shared notebook, with no way to pin an older one.
notebookutils.notebook.run for orchestration
notebookutils.notebook.run runs another notebook and returns its exit value. runMultiple runs several, in parallel
or as a dependency graph, inside one Spark session:
exit_value = notebookutils.notebook.run("nb_ingest_north", 600, {"landing_folder": "Files/landing/north/"})
results = notebookutils.notebook.runMultiple(["nb_ingest_north", "nb_ingest_south", "nb_ingest_east"])
for name, outcome in results.items():
print(name, outcome["exitVal"], outcome["exception"])
The child ends with notebookutils.notebook.exit("...") in its own cell, outside any try block: Microsoft notes that
“the exit won’t take effect when wrapped in exception handling”. The documented behaviour worth knowing:
- The return value is always a string. Convert it yourself (
int(exit_value)). - The reference run “runs on the Spark pool of the notebook that calls this function”, and
runMultiple’s notebooks share that session’s compute. - A child notebook runs only if it uses the same default lakehouse as the parent, inherits it, or neither defines one.
%%configurein the child is ignored, and inline%pipcommands aren’t supported in reference runs.- Each run’s output includes a snapshot link for debugging.
This is the tool for running one notebook per merchant or a set of notebooks in dependency order. It isn’t a way to
share functions: the ingestion notebooks it runs still need the rules from an import or %run.
These notebookutils calls exist only inside Fabric, so they weren’t executed for this article; they follow the
documented signatures.
Existing third-party libraries
Before writing your own, look for one that already exists. For most data engineering problems, it does.
- Use the platform first. In Spark, the functions in
pyspark.sql.functionsrun inside the engine. They beat almost any Python reimplementation, and they are maintained by the Spark project. The same goes for Delta Lake’sMERGE, Fabric’s built-in connectors and the Fabric Runtime’s preinstalled libraries. - Use established open-source libraries for well-understood problems: data validation, date handling, HTTP clients, file formats. Their maintainers have already found the edge cases you haven’t hit yet.
- Check the cost of the dependency, not only its features: license, maintenance activity, security history, transitive dependencies, and whether it supports your runtime’s Python and Spark versions. A dependency that blocks your next runtime upgrade isn’t free.
A good rule: if a well-maintained library solves 90% of the problem, write a thin wrapper for the remaining 10% instead of a new library.
In Fabric, the runtime’s built-in libraries “are installed by default in every environment and can’t be changed”.
Anything else comes from an Environment’s public libraries (PyPI or conda), a private feed, or a wheel file you upload.
Pin versions there, as you would in any requirements.txt.
5. One example, three stages: the merchant notebooks
A fictional payments company receives merchant files from three partners. Three notebooks, nb_ingest_north,
nb_ingest_south and nb_ingest_east, each read a CSV delivery from the lakehouse, clean it and keep the valid rows.
The rules are the same everywhere: trim and uppercase the merchant ID and country code, parse the amount, and reject
rows with no merchant, a country code that isn’t two letters, an amount that can’t be parsed, or a negative amount.
- Stage 1Repeated notebook codeThe same cell, copied into three notebooks
- Stage 2Shared Python moduleOne merchant_rules.py, unit-tested once
- Stage 3Versioned packagemerchant-rules 1.0.0, installed from an Environment
Stage 1: the same cell in three notebooks
The first notebook has this cell, and the other two notebooks start as copies of it:
from pyspark.sql import functions as F
raw = spark.read.option("header", True).csv("Files/landing/north/")
clean = (
raw.withColumn("merchant_id", F.upper(F.trim("merchant_id")))
.withColumn("country", F.upper(F.trim("country")))
.withColumn("amount", F.col("amount").cast("decimal(18,2)"))
)
valid = clean.filter(
F.col("merchant_id").isNotNull() & (F.length("country") == 2) & (F.col("amount") >= 0)
)It looks fine, and on clean data it is. We ran it on a six-row synthetic file with two valid rows and four that each
break one rule, one of them an amount written 12,50 with a decimal comma:
- With ANSI mode off (the default in Spark 3.5), the cast turns
12,50into null and the filter drops it. The cell keeps the two valid rows, and the other four disappear without any record of why. - With ANSI mode on (the default since Apache Spark 4.0, which we observed with PySpark 4.1.4), the same cast fails
the whole job on
12,50.
The same code behaves differently depending on a session setting, and the fix has to be made in three notebooks. Over
time the copies also drift: one notebook adds a rule, another relaxes >= 0 to accept refunds, and nobody can say
which version is correct. Check your runtime’s setting with spark.conf.get("spark.sql.ansi.enabled") rather than
assuming it.
Stage 2: one shared module
The rules move into one file, merchant_rules.py. The logic takes a DataFrame and returns DataFrames; reading files
and writing tables stays in the notebooks.
"""Merchant normalization and validation rules shared by the ingestion notebooks."""
from pyspark.sql import Column, DataFrame
from pyspark.sql import functions as F
REQUIRED_COLUMNS = ("merchant_id", "country", "amount")
def normalize(df: DataFrame) -> DataFrame:
"""Trim and uppercase the keys; an amount that can't be parsed becomes null."""
missing = [name for name in REQUIRED_COLUMNS if name not in df.columns]
if missing:
raise ValueError(f"missing required columns: {missing}")
return (
df.withColumn("merchant_id", F.upper(F.trim("merchant_id")))
.withColumn("country", F.upper(F.trim("country")))
.withColumn("amount", F.expr("try_cast(amount AS DECIMAL(18,2))"))
)
def rejection_reason() -> Column:
"""The first rule a normalized row breaks, or null when it passes them all."""
return (
F.when(F.col("merchant_id").isNull() | (F.col("merchant_id") == ""), "missing merchant_id")
.when(F.col("country").isNull() | ~F.col("country").rlike("^[A-Z]{2}$"), "invalid country")
.when(F.col("amount").isNull(), "invalid amount")
.when(F.col("amount") < 0, "negative amount")
)
def split_valid(df: DataFrame) -> tuple[DataFrame, DataFrame]:
"""Return (valid rows, rejected rows with a rejection_reason column)."""
checked = normalize(df).withColumn("rejection_reason", rejection_reason())
valid = checked.filter(F.col("rejection_reason").isNull()).drop("rejection_reason")
rejected = checked.filter(F.col("rejection_reason").isNotNull())
return valid, rejected
Three things changed besides the location. try_cast makes an unparseable amount null whatever the ANSI setting, so
the behaviour no longer depends on the session. Every row ends up in exactly one of two DataFrames, and rejected rows
say why. And the function checks its required columns, so a renamed source column fails immediately with a clear
message instead of producing an empty result.
Because it’s a plain module, it can be tested with pytest and a local Spark session, with no Fabric workspace:
from decimal import Decimal
from merchant_rules import split_valid
def test_split_valid_keeps_every_row_and_says_why(spark):
raw = spark.createDataFrame(
[(" m-001 ", "us", "12.50"), ("m-004", "USA", "3.00"), ("m-006", "de", "12,50")],
["merchant_id", "country", "amount"],
)
valid, rejected = split_valid(raw)
assert [tuple(r) for r in valid.collect()] == [("M-001", "US", Decimal("12.50"))]
assert sorted(r.rejection_reason for r in rejected.collect()) == ["invalid amount", "invalid country"]
The spark fixture is a local session created once per test run, as described in
PySpark DataFrame unit testing with pytest. This test and the
others in the example pass, unchanged, with PySpark 3.5.5, 4.1.4 and 4.3.0, with ANSI mode on and off.
Getting the module into Fabric. There are three routes at this stage, each with its own import path.
Route 1: notebook resources. Upload the file to builtin/shared/merchant_rules.py in a notebook’s resources
folder, then import it with the documented builtin.<folder>.<module> form:
import builtin.shared.merchant_rules as merchant_rules
raw = spark.read.option("header", True).csv("Files/landing/north/")
valid, rejected = merchant_rules.split_valid(raw)The resources folder belongs to one notebook, so each of the three notebooks needs its own upload. Unless the folders are committed to Git and kept in sync, that’s three copies again.
Route 2: a shared notebook and %run. Put the module’s code in a notebook named nb_merchant_rules, and start each
ingestion notebook with a cell containing %run nb_merchant_rules. split_valid is then defined in the caller.
There’s one copy for the workspace, reviewed like any notebook, but every caller always runs the latest version.
Route 3: an Environment custom .py file. Upload merchant_rules.py to an Environment’s custom libraries, publish,
and attach the Environment to the three notebooks. One copy, shared beyond a single notebook; confirm the import name in
a test notebook first, as noted in section 4.
Stage 2 is often where teams should stay for a while. One implementation is tested, the copies are gone, and the rules can still change quickly while their shape settles.
Stage 3: a versioned package
When several teams, workspaces or pipelines depend on the rules, the missing pieces are a version number, a release
process and an owner. The same file becomes the rules module of a package:
stage3_package/
pyproject.toml
src/merchant_rules/__init__.py
src/merchant_rules/rules.py # the stage 2 module, unchanged
src/merchant_rules/py.typed
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
[project]
name = "merchant-rules"
version = "1.0.0"
description = "Merchant normalization and validation rules for the ingestion notebooks"
requires-python = ">=3.10"
dependencies = [] # PySpark is provided by the Fabric runtime; don't pin it here
[project.optional-dependencies]
test = ["pytest>=8", "pyspark>=3.5"]
[tool.hatch.build.targets.wheel]
packages = ["src/merchant_rules"]
__init__.py re-exports the public functions and sets __version__ = "1.0.0". python -m build stage3_package
produces merchant_rules-1.0.0-py3-none-any.whl, which contains only the package and its metadata. Uploaded to an
Environment, published and attached, it’s imported by its package name:
from merchant_rules import split_valid
raw = spark.read.option("header", True).csv("Files/landing/north/")
valid, rejected = split_valid(raw)Nothing in the rules changed between stage 2 and stage 3, and a test checks that rules.py is byte-for-byte the stage 2
module. What changed is around the code: the wheel name says which version a pipeline runs, a changelog says what
changed, and an upgrade is a deliberate step instead of a side effect of someone editing a shared notebook.
Versioning also forces useful questions. Suppose the business decides that zero amounts are invalid. That makes rows that were valid yesterday rejected today: a behaviour change for every consumer, so a major version (2.0.0) or an opt-in parameter, not a quiet patch.
6. Comparing maintainability, operations and performance
The tables compare the five ways to share the merchant rules. notebookutils.notebook.run isn’t in them: it
orchestrates notebooks rather than sharing logic, so compare it with a Data Factory pipeline instead. Third-party
libraries behave like an Environment wheel that someone else maintains.
Development and quality
| Copied cells | Notebook resources module | Shared notebook with %run |
Environment .py file |
Environment wheel | |
|---|---|---|---|---|---|
| Development effort | Lowest to start | Low: one file, uploaded per notebook | Low: one notebook | Low, plus an Environment publish | Highest: packaging, build, release |
| Code duplication | One copy per notebook | One copy per notebook’s folder | One copy per workspace | One copy per Environment | One versioned artifact |
| Testing | Rarely tested | Testable locally if the file also lives in a repository | Hard: tests have to run the notebook | Testable locally | Unit tests, plus a built artifact tested before release |
| Debugging | Code visible in the cell | Tracebacks point to the module file | Code runs inline, cell by cell | Installed code, not visible in the notebook | Installed code; reproduce with local tests and the exact version |
| Code review | Each copy separately, if at all | Per notebook, unless resources are in Git | As notebook changes in Git | With the Environment in Git | In the library’s repository, with a changelog |
Release and operations
| Copied cells | Notebook resources module | Shared notebook with %run |
Environment .py file |
Environment wheel | |
|---|---|---|---|---|---|
| Versioning | None | Git history at best | None: every caller runs the latest | Environment publish history only | Semantic version in the file name and metadata |
| Deployment | Edit every notebook | Upload to every notebook, or sync through Git | Deploy one notebook | Publish the Environment; deployment pipelines carry its contents | Build once, publish, promote the same file |
| Environment compatibility | Per notebook | Per notebook | Per workspace runtime | Per Environment runtime | Declared (requires-python) and tested against your runtime |
| Team ownership | Whoever copied last | Each notebook’s owner | The shared notebook’s owner | The Environment’s owner | A named library owner and release process |
| Dependency management | Implicit, per notebook | Implicit | Implicit: whatever the shared notebook imports | The Environment’s library list | Declared in pyproject.toml; resolved at publish in Full mode |
Performance
| Copied cells | Notebook resources module | Shared notebook with %run |
Environment .py file |
Environment wheel | |
|---|---|---|---|---|---|
| Compute startup | Nothing added | No startup cost documented | The referenced cells run on every %run: definitions are quick, but any Spark action in them runs too |
Installed with the Environment’s libraries (see below) | Same as an Environment .py file |
| Runtime execution | Same code, same speed | Same | Same | Same | Same |
The last row is the important one. The same function runs at the same speed whichever way it reached the notebook. The Python interpreter executes the same bytecode, and Spark gets the same plan.
Startup is where the options differ, and it depends on your setup. Microsoft documents that in Full publish mode, “session startup adds 1 to 3 minutes for dependency deployment, depending on dependency size”. In Quick mode, packages “install when the first code cell for that language runs”. Those are Microsoft’s ranges for its own scenarios, not a cost to expect for one small wheel. A large Environment with many dependencies can lengthen session start; a single pure-Python wheel may add little. Measure session start in your workspace, separately from execution (section 14 explains how). Microsoft also documents a way to keep a stable snapshot with fast starts: Full mode together with a custom live pool.
What a shared version gives you, and what it costs
The real benefits of a well-run library are not about speed.
| Benefit | What it gives you | What it costs |
|---|---|---|
| Consistency | One implementation of a rule; reports that agree | Callers must upgrade to get fixes |
| Testing | Unit tests run once, in CI, against the library | Someone has to write and maintain them |
| Reliability | A fix ships to every pipeline with a version bump | A bad release also ships everywhere |
| Ownership | A named owner, a changelog, a support channel | Real time from that owner |
| Upgrades | One package to validate against a new runtime | Every consumer still needs a smoke test |
Testing is where a library pays off most clearly. A pure Python function inside a package can be unit-tested with pytest on a laptop, without a Spark cluster. PySpark transformations can be tested with a local session, as described in PySpark DataFrame unit testing with pytest. Code that lives in six notebooks is, realistically, never tested at all.
7. When to build an internal shared library
Build one when the logic is yours: it encodes business rules, conventions or platform decisions no external library can know about, and several pipelines depend on it.
Good candidates:
- Business rules applied in several places: currency conversion conventions, fiscal calendars, customer-key normalization, the definition of an “active” account.
- Platform conventions: standard audit columns, naming rules for Delta tables, logging and error handling that every notebook should share.
- Reviewed decisions you want to reuse, such as approved column mappings. JaviMapper is an example: the mapping logic and the approval workflow live in one tested package, and each pipeline only loads its reviewed mapping file.
- Tooling around your own workflow, such as a consistent way to benchmark a change before merging it. JaviPerf is an example of that kind.
Section 9 turns these questions into a decision tree, including when a shared module is enough and when a versioned package is worth its cost.
8. When not to create a library
A library has a fixed cost: packaging, versioning, testing, documentation, releases and support questions. Don’t pay it when:
- The code is used once. Reuse is the whole point. One caller doesn’t need a public API.
- The logic is still changing every week. Versioning code that changes daily creates release overhead without stability. Let it settle in a module first.
- The “shared” logic is actually different everywhere. If every caller needs a different flag, the library becomes a pile of options that nobody understands. Two honest copies can be better than one dishonest abstraction.
- Nobody will own it. An orphaned internal library is worse than copied code: everyone depends on it and nobody can fix it.
- The platform already does it. Wrapping
spark.read.format("delta")in a function calledread_tableadds indirection, not value. - Your team can’t release it yet. A wheel needs somewhere to build it, test it and publish it. Until that exists, a
tested module delivered through
%runor an Environment.pyfile gives most of the benefit with less process. - You need orchestration, not reuse. If the goal is to run the same notebook for each merchant, use
notebookutils.notebook.runMultipleor a pipeline, and keep the logic where it is.
9. Choosing an approach
The number of notebooks isn’t the deciding factor. Three notebooks with rules that change every week are better served by a shared notebook than by a release process; one notebook that a finance report depends on may deserve a tested package. Start from what you need from the other code, and from how stable and how shared it is.
- Code needed elsewhereLogic, or a whole notebook run
- What do you need from it?
- one placeKeep it in the notebookExploration, one-off or source-specific logic
- a workflowRun it as a stepnotebookutils.notebook.run, runMultiple or a pipeline
- still changingShare a module%run a shared notebook, or an Environment .py file
- stable, sharedVersion a packageA wheel in an Environment, with an owner and releases
- not yoursUse an existing librarySpark built-ins, the runtime, maintained open source
Comparison matrix
| Approach | Best when | Watch out for |
|---|---|---|
| Code in the notebook | Used in one place, or still being explored | Becoming the template that everyone copies |
| Copied code | Two pipelines whose rules are meant to diverge | Fixes that reach only one copy |
.py module in a repository |
You want tests and one source of truth | It still needs a delivery route into Fabric |
| Notebook resources | One notebook needs helper code or files next to it | It’s per notebook; relative paths don’t work in high concurrency sessions |
Environment .py file |
Several notebooks share a small module | No version or declared dependencies; confirm the import name |
| Environment wheel | Stable logic shared across teams, pipelines or workspaces | Release overhead; startup impact of Environment libraries |
%run |
Shared helpers or setup within one workspace | No pinning; hidden names; the referenced cells run every time |
notebookutils.notebook.run |
Running notebooks as steps, in parallel or in order | Returns only a string; same-lakehouse rule; shared session compute |
| Third-party library | A generic problem that others already solve well | Dependency cost, licensing, runtime compatibility, blocked PyPI on private networks |
Five scenarios
1. An analyst cleans a one-off extract. A notebook fixes a supplier’s file once, for an investigation. Choose: code in the notebook. Why: there’s no second caller, and the logic is specific to that file. Watch for: the notebook becoming a template. If a second pipeline needs the cleanup, move to a module then.
2. Three ingestion notebooks, one team, rules still changing. This is stage 2 of the merchant example.
Choose: a module tested in Git, delivered through a shared notebook with %run or an Environment .py file.
Why: one implementation and real tests, without release overhead while the rules settle. Watch for: every caller
runs the latest version, so a change to the shared notebook is a change to all three pipelines at once.
3. Finance-critical rules used by twelve pipelines in four workspaces. Ownership is split across teams, and
deployments go through Git and deployment pipelines.
Choose: a versioned wheel in an Environment, published in Full mode, promoted from a test Environment.
Why: %run can’t cross workspaces, and twelve consumers need to know exactly which version they run.
Watch for: release discipline. A stricter rule is a breaking change, and session start should be measured after
adding the Environment.
4. A nightly run for each merchant feed, then a reconciliation.
Choose: notebookutils.notebook.runMultiple with a dependency graph (or a pipeline), with each ingestion notebook
importing the rules from the package. Why: this is orchestration and reuse at the same time, and each tool does one
of the two. Watch for: the children share the session’s compute, exit values are strings, and each child must use
the same default lakehouse as the orchestrator (or inherit it).
5. Parsing awkward dates, retrying an HTTP API, validating schemas. Choose: Spark’s built-in functions where they exist, otherwise a maintained third-party library installed in the Environment with a pinned version. Why: these problems aren’t yours, and others have already found the edge cases. Watch for: with outbound access protection or managed virtual networks, public PyPI is blocked, so plan to supply wheel files or a reachable private feed.
10. Common mistakes
- Expecting
notebookutils.notebook.runto return data. It returns the child’s exit string. Write results to a table and pass the table name, or return a small value such as a row count. - Using
%runas a production library. It works, until a change to the shared notebook reaches every caller at the same moment, with no version to roll back to. - Uploading the same
.pyfile to every notebook’s resources. That’s copying with extra steps. Use an Environment, or a shared notebook. %pip installin scheduled notebooks. Inline installs are disabled in pipeline runs by default, aren’t supported in high concurrency mode or reference runs, and every run pays the installation again.- Wrapping
notebookutils.notebook.exitintry/except. Microsoft documents that the exit then doesn’t take effect. - Pinning PySpark as a dependency of your wheel. The Fabric runtime provides Spark; a different PySpark pulled in by your package can break the session.
- Putting I/O inside the shared logic. A function that reads a hard-coded path or writes a table can’t be tested without that path or table. Pass DataFrames in and return DataFrames.
- Releasing a stricter rule as a patch. If rows that were valid become rejected, consumers’ results change. That’s a major version, or an opt-in.
- Claiming a speed-up from packaging. Moving code into a library doesn’t make it faster. If it got faster, something else changed; find out what (section 11).
- Relying on relative
builtin/paths in a high concurrency session. Microsoft notes they don’t work there.
11. Can a library actually improve performance?
Indirectly, yes. Directly, no.
Importing a function from a wheel instead of defining it in a notebook cell doesn’t change how fast it runs. The Python interpreter executes the same bytecode either way. What can change performance is what the shared code does differently:
- Better algorithms in one place. If the shared implementation uses a vectorized or built-in operation where the copies used a row-by-row loop, every caller gets faster when it switches. The library didn’t do that; the algorithm did.
- Engine-native operations. A shared helper that expresses cleanup with
pyspark.sql.functionsinstead of a Python UDF keeps the work inside Spark’s engine. - Avoiding repeated mistakes. A shared reader that always selects only the needed columns, or a writer that always targets sensible file sizes, prevents the same performance bug in every pipeline.
- Less startup work. Installing a stable library once in a Fabric Environment, instead of running
%pip installin every notebook, removes install time from each run. That’s session start-up time, not faster code; see How to reduce Fabric notebook startup time.
The library is the delivery mechanism for these improvements, not their cause. That distinction matters when someone says “we moved it into a library and it got faster”: ask what else changed.
How a library helps teams use the better implementation
What a library does change is how consistently the faster, correct version is used. In the merchant example, the
copied cells used cast, whose behaviour depends on the session’s ANSI setting; the shared module uses try_cast and
built-in column functions, and every notebook that imports it gets that choice without anyone re-deriving it. The same
applies to performance work:
- Validate once, reuse everywhere. When one implementation has been measured on representative data and checked to give the same output, a library is how that validated version reaches every pipeline.
- Make the efficient path the easy one. A shared helper built on
pyspark.sql.functionskeeps callers away from row-by-row UDFs without each of them having to know why. - Guard it in tests. A test can check the physical plan of a shared transformation, for example that it contains no Python UDF, so a regression fails in CI instead of in production.
None of this is automatic, and none of it comes with a guaranteed speed-up: the gain is whatever the better implementation gives on your data, measured as in sections 12 and 14.
12. Performance overhead and bad abstractions
Abstraction can also make code slower. A common pattern in internal libraries is a generic “pipeline of steps”, where
each step is an object with an apply(row) method and defensively copies the row so steps can’t interfere with each
other. It’s tidy, configurable and easy to extend. It’s also a lot of extra work per row.
class Step:
def apply(self, row: dict) -> dict:
raise NotImplementedError
class StripCountry(Step):
def apply(self, row):
out = dict(row) # defensive copy, every row, every step
out["country"] = out["country"].strip()
return out
# ... UpperCountry and AmountToCents follow the same pattern ...
def run_pipeline(rows, steps):
result = []
for row in rows:
for step in steps:
row = step.apply(row)
result.append(row)
return result
def direct(rows):
return [{"order_id": r["order_id"], "country": r["country"].strip().upper(),
"amount_cents": round(r["amount"] * 100)} for r in rows]
Both produce identical output. We measured them with JaviPerf on 200,000 synthetic rows: two warm-up runs, five measured runs each, interleaved, with an equivalence check outside the timed region.
In this run, the direct version’s median was about 40% of the pipeline’s. That number describes one machine and one synthetic dataset; on yours it will differ. The lesson does generalize: per-row object calls and copies are not free, and a library that forces them on every caller spreads that cost everywhere.
That doesn’t make abstraction bad. It means the abstraction should sit at the right level: a shared function that takes a whole list or a whole DataFrame, rather than a framework that is called once per row.
In Spark, the same problem takes a bigger form. A shared helper implemented as a Python UDF moves every row between
the JVM and a Python worker, where the optimizer can’t see inside it. JaviPerf’s plan analysis flags this as
PYTHON_UDF without running anything. A version using F.upper(F.trim(...)) has no such operator.
13. Example: one mapping library across several Fabric notebooks
Here is what reuse looks like when it works. Several ingestion notebooks receive files from different merchants, each with its own column names. Instead of each notebook carrying its own rename logic, each one loads a reviewed mapping file and applies it with the same library function.
from javimapper import ApprovedMapping
from javimapper.adapters.spark import apply_mapping
# Notebook A: merchant "north" (the mapping was reviewed and approved once, then saved as JSON)
north_mapping = ApprovedMapping.load("/lakehouse/default/Files/mappings/north.mapping.json")
north = apply_mapping(spark.read.option("header", True).csv("Files/landing/north/"), north_mapping,
unmapped="drop", order="target")
# Notebook B: merchant "south", same library, same function, its own reviewed mapping
south_mapping = ApprovedMapping.load("/lakehouse/default/Files/mappings/south.mapping.json")
south = apply_mapping(spark.read.option("header", True).csv("Files/landing/south/"), south_mapping,
unmapped="drop", order="target")
What the library owns: the matching rules, the approval workflow, the mapping file format and the adapter that applies
it as one lazy select. What each notebook owns: which file to read, which reviewed mapping to use, and where the
result goes. When the adapter gets a fix, every notebook picks it up with a new version of the wheel in the shared
Environment. No notebook has to be edited.
The JaviMapper hands-on lab walks through this with three synthetic merchant schemas, including running it in Microsoft Fabric.
JaviMapper is stage 3 of this article’s example, applied to schema mapping: one versioned package, many notebooks, and reviewed mapping files as the only per-pipeline input.
14. Example: measuring and investigating with JaviPerf
JaviPerf was written to make the measurements in this article repeatable. It is experimental: version 0.2, tested locally against Spark 3.5.5, 4.1.4 and 4.3.0, and run once in Microsoft Fabric in a private lab run. It does three things, and keeps their results apart:
- Measured runtime behaviour: warm-up and repeated runs, failures kept, median and spread reported, and an interleaved before/after comparison with an equivalence check.
- Static plan observations: what a Spark physical plan contains (shuffles, sorts, Python UDFs, broadcast and
nested-loop joins, cached data, repeated scans), read from
explain()without running a job. - Investigations to validate: where to look next. These are hypotheses, not fixes.
The notebook below was executed locally (PySpark 4.1.4, Python 3.13, synthetic data). Its outputs are real, and your numbers will differ.
Notebook: javiperf-quickstart.ipynb
Read-only view of the notebook file. Nothing on this page runs code.
Cell 7Markdown3. Read a Spark plan without running it
3. Read a Spark plan without running it
analyze_dataframereadsexplain(mode="simple"). It launches no Spark job and collects nothing.Cell 8PySparkRead a plan without running it17 lines
from pyspark.sql import functions as F from pyspark.sql.types import StringType source = spark.range(0, 200_000).select("id", F.concat(F.lit(" c"), (F.col("id") % 100).cast("string")).alias("code")) normalize = F.udf(lambda s: s.strip().upper(), StringType()) def with_udf(): return source.select("id", normalize("code").alias("code")) def with_builtin(): return source.select("id", F.upper(F.trim("code")).alias("code")) for label, build in (("Python UDF", with_udf), ("built-in functions", with_builtin)): analysis = analyze_dataframe(build(), label=label) print(f"{label}: {', '.join(analysis.codes) or 'no findings'}") for f in analysis.findings: print(f" {f.code} [{f.level}] {'; '.join(f.evidence)}")Output
Python UDF: PYTHON_UDF PYTHON_UDF [review] Python execution operators: BatchEvalPython × 1; BatchEvalPython evaluates a row-at-a-time Python UDF (pickled rows, not Arrow batches) built-in functions: no findings
Cell 9Markdown4. Time Spark with an explicit action
4. Time Spark with an explicit action
Building a DataFrame does no work. Timing it without an action is the classic mistake: JaviPerf counts the Spark jobs each run started and warns when there were none.
Cell 10PySparkTime Spark with an explicit action9 lines
lazy = benchmark_dataframe("no action", with_builtin, action=lambda df: df, spark=spark, warmup=1, repeat=3) print("no action, Spark jobs per run:", [r.observations["spark_jobs"] for r in lazy.measured_runs]) print("warning:", any("No Spark job was observed" in n for n in lazy.notes)) spark_comparison = compare_dataframes("UDF vs built-in", with_udf, with_builtin, action=materialize_noop, spark=spark, warmup=1, repeat=3) print("noop write, Spark jobs per run:", [r.observations["spark_jobs"] for r in spark_comparison.candidate.measured_runs]) print("equivalence:", spark_comparison.equivalence) print("verdict: ", spark_comparison.verdict)Output
no action, Spark jobs per run: [0, 0, 0] warning: True noop write, Spark jobs per run: [1, 1, 1] equivalence: equivalent verdict: candidate_faster
Not shown here: cells 1, 2, 3, 4, 5, 6, 11, 12. Open the full notebook (all 12 cells, in order)
The last cell shows the trap that catches most Spark benchmarks. Spark transformations are lazy: building a DataFrame returns immediately and does no work. Time it without an action and you’ve measured plan construction.
That’s why JaviPerf’s Spark helpers require an explicit action, such as materialize_noop, which executes the whole
plan through Spark’s built-in noop writer without writing or collecting anything. Each run’s Spark jobs are counted,
and a run that started none is flagged. Even then, a Spark timing is sensitive to things no library controls: cached
data, adaptive query execution changing the plan between runs, first-run overhead, other workloads on the same capacity,
and session state.
A faster run is also not automatically a cheaper one. Fabric capacity consumption depends on how compute is metered, not only on how long a notebook takes. Treat elapsed time as one signal, and confirm cost effects in Fabric’s own capacity metrics.
Startup and execution are different measurements
“The notebook took three minutes” mixes several things: waiting for a Spark session, the first Spark job, the actual work, and gaps between cells. They have different causes, and different fixes:
- Session startup runs from the request for compute until a session can run code. It includes queueing and, with Full-mode Environment libraries, library deployment, which Microsoft documents as adding 1 to 3 minutes to session start. It can’t be timed from inside the notebook, because no cell runs until the session is ready. Use Fabric’s Session Start Insights (Session Details), the Spark monitoring API’s Livy session timestamps, or a clock and a note. In the first live lab run, the startup duration and delay reason were in the notebook’s View session information panel (the arrow next to Standard session), as a duration without timestamps.
- The first Spark action pays one-time costs (scheduling, executor start, code paths loaded for the first time). The same small action run again is typically much faster.
- Execution is the work your code asks for, and only an action runs it.
What a library can measure automatically is the last two: phases inside the notebook, Spark job counts, and plans. Startup, queueing and contention from other workloads need Fabric’s monitoring or timestamps you record. JaviPerf 0.2 records both kinds side by side, each with its source and precision, and never adds durations that come from different clocks or overlap.
When session reuse helps. Reusing a running session (interactive iteration, or high concurrency, which Microsoft documents as sharing a session within one user, with the same default lakehouse and compute settings) removes startup from that run. It doesn’t make the code faster, and a measurement taken in a reused session is not a cold-start measurement. JaviPerf reports a reused session’s startup as not applicable rather than zero.
When an optimization is worth investigating. Look at the phase that dominates. If startup dominates a short notebook, tuning its code changes little: the pool, the Environment and session reuse matter more. If execution dominates, the plan observations and a before/after comparison on representative data are where to start. And in every case, check correctness first: a faster version that returns different rows isn’t an improvement.
- Measure the phasesStartup, first action, execution
- waitingStartup dominatesPool type, Environment libraries, session reuse
- first jobFirst action dominatesOne-time cost; check it repeats per session
- the workExecution dominatesPlan observations, before/after with equivalence
The JaviPerf hands-on lab walks through a first measurement of each phase in Fabric.
Its first live run (November 30, 2026) has one startup observation: Fabric reported 28.843 seconds for a
starter-pool session whose Environment held two custom libraries, with the delay reason CustomLibraries. That is a
single observation without a baseline: it doesn’t show how much the libraries added, or what a typical start takes.
The complete notebook, with every cell and its saved output:
Notebook: javiperf-quickstart.ipynb
Read-only view of the notebook file. Nothing on this page runs code.
Cell 1MarkdownJaviPerf quickstart: measure, compare, and read a Spark plan
JaviPerf quickstart: measure, compare, and read a Spark plan
JaviPerf 0.1 is experimental. This notebook uses synthetic data only. The saved outputs were captured on a local machine (PySpark with a local master), not in Microsoft Fabric. Your numbers will differ: the point is the method.
It runs unchanged in a Fabric notebook attached to an Environment that has the JaviPerf wheel as a custom library, because it uses the
sparksession the notebook provides when there is one.Cell 2PySparkCode14 lines
import sys import javiperf from javiperf import build_report, compare, measure, render_html, run_benchmark from javiperf.spark import analyze_dataframe, benchmark_dataframe, compare_dataframes, materialize_noop try: spark # provided by Microsoft Fabric and other Spark notebook hosts where = "notebook session" except NameError: from pyspark.sql import SparkSession spark = SparkSession.builder.master("local[2]").config("spark.ui.enabled", "false").getOrCreate() where = "local session" print(f"JaviPerf {javiperf.__version__} | Python {sys.version.split()[0]} | Spark {spark.version} ({where})")Output
JaviPerf 0.1.0 | Python 3.13.17 | Spark 4.1.4 (local session)
Cell 3Markdown1. Measure, then repeat
1. Measure, then repeat
One timing is one observation.
run_benchmarkadds warm-up runs (recorded, not summarized) and repeated runs.Cell 4PySparkCode13 lines
rows = [{"order_id": i, "country": " ca " if i % 3 else "us"} for i in range(100_000)] def clean(data): return [(r["order_id"], r["country"].strip().upper()) for r in data] with measure("clean once") as m: clean(rows) print(f"single run: {m.status}") result = run_benchmark("clean", lambda: clean(rows), warmup=2, repeat=7) s = result.summary print(f"{s.count} measured runs, {len(result.failed_runs)} failed") print(f"spread: CV {s.cv:.1%}, max/min {s.max_s / s.min_s:.2f}")Output
single run: ok 7 measured runs, 0 failed spread: CV 5.7%, max/min 1.17
Cell 5Markdown2. When an abstraction costs more than it saves
2. When an abstraction costs more than it saves
A generic "pipeline of steps" that copies each row at every step, against a direct comprehension.
equivalent=checks that both produce the same rows, outside the timed region.Cell 6PySparkCode25 lines
class Step: def apply(self, row): raise NotImplementedError class Strip(Step): def apply(self, row): out = dict(row); out["country"] = out["country"].strip(); return out class Upper(Step): def apply(self, row): out = dict(row); out["country"] = out["country"].upper(); return out def run_steps(data, steps): result = [] for row in data: for step in steps: row = step.apply(row) result.append((row["order_id"], row["country"])) return result comparison = compare(lambda: run_steps(rows, [Strip(), Upper()]), lambda: clean(rows), name="generic steps vs direct", warmup=2, repeat=7, equivalent=lambda a, b: a == b) print("equivalence:", comparison.equivalence) print("verdict: ", comparison.verdict, "-", comparison.verdict_reason) print(f"observed median ratio (direct / steps): {comparison.median_ratio:.2f}")Output
equivalence: equivalent verdict: candidate_faster - Every successful candidate run was faster than every successful baseline run in this session. observed median ratio (direct / steps): 0.26
Cell 7Markdown3. Read a Spark plan without running it
3. Read a Spark plan without running it
analyze_dataframereadsexplain(mode="simple"). It launches no Spark job and collects nothing.Cell 8PySparkCode17 lines
from pyspark.sql import functions as F from pyspark.sql.types import StringType source = spark.range(0, 200_000).select("id", F.concat(F.lit(" c"), (F.col("id") % 100).cast("string")).alias("code")) normalize = F.udf(lambda s: s.strip().upper(), StringType()) def with_udf(): return source.select("id", normalize("code").alias("code")) def with_builtin(): return source.select("id", F.upper(F.trim("code")).alias("code")) for label, build in (("Python UDF", with_udf), ("built-in functions", with_builtin)): analysis = analyze_dataframe(build(), label=label) print(f"{label}: {', '.join(analysis.codes) or 'no findings'}") for f in analysis.findings: print(f" {f.code} [{f.level}] {'; '.join(f.evidence)}")Output
Python UDF: PYTHON_UDF PYTHON_UDF [review] Python execution operators: BatchEvalPython × 1; BatchEvalPython evaluates a row-at-a-time Python UDF (pickled rows, not Arrow batches) built-in functions: no findings
Cell 9Markdown4. Time Spark with an explicit action
4. Time Spark with an explicit action
Building a DataFrame does no work. Timing it without an action is the classic mistake: JaviPerf counts the Spark jobs each run started and warns when there were none.
Cell 10PySparkCode9 lines
lazy = benchmark_dataframe("no action", with_builtin, action=lambda df: df, spark=spark, warmup=1, repeat=3) print("no action, Spark jobs per run:", [r.observations["spark_jobs"] for r in lazy.measured_runs]) print("warning:", any("No Spark job was observed" in n for n in lazy.notes)) spark_comparison = compare_dataframes("UDF vs built-in", with_udf, with_builtin, action=materialize_noop, spark=spark, warmup=1, repeat=3) print("noop write, Spark jobs per run:", [r.observations["spark_jobs"] for r in spark_comparison.candidate.measured_runs]) print("equivalence:", spark_comparison.equivalence) print("verdict: ", spark_comparison.verdict)Output
no action, Spark jobs per run: [0, 0, 0] warning: True noop write, Spark jobs per run: [1, 1, 1] equivalence: equivalent verdict: candidate_faster
Cell 11Markdown5. Report
5. Report
One self-contained HTML file: measured behaviour, static plan observations, investigations to validate, and the limitations. In Fabric,
displayHTMLshows it inline.Cell 12PySparkCode10 lines
report = build_report(title="JaviPerf quickstart", benchmarks=[result], comparisons=[comparison, spark_comparison], plan_analyses=[analyze_dataframe(with_udf(), label="Python UDF")]) html = render_html(report) try: displayHTML(html) # Fabric and Synapse notebooks except NameError: from pathlib import Path Path("javiperf-report.html").write_text(html, encoding="utf-8") print(f"report written: javiperf-report.html ({len(html) // 1024} KB, no scripts, no external resources)")Output
report written: javiperf-report.html (20 KB, no scripts, no external resources)
15. Building a Python wheel
A wheel is built from a project with a pyproject.toml. The Python Packaging User Guide describes the standard flow:
a build front-end (build) asks a build backend (here, hatchling) to produce a source distribution and a wheel.
# pyproject.toml (excerpt)
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
[project]
name = "javiperf"
version = "0.2.0"
requires-python = ">=3.10"
dependencies = [] # the core needs only the standard library
license = "Apache-2.0"
[project.optional-dependencies]
spark = ["pyspark>=3.5"] # optional: Fabric already provides PySpark
python -m pip install --upgrade build
python -m build libraries/javiperf # writes dist/javiperf-0.2.0-py3-none-any.whl and dist/javiperf-0.2.0.tar.gz
A few habits make a wheel easier to run in a managed runtime:
- Keep run-time dependencies minimal, and don’t pin PySpark as a hard dependency. Fabric’s runtime provides Spark. A wheel that pulls in a different PySpark can break the session.
- Declare
requires-pythonto match what you have tested. - Make it pure Python if you can (
py3-none-any). It then installs on any platform without compilation. - Inspect the wheel before sharing it (
python -m zipfile -l dist/*.whl): no tests, no data, no credentials.
16. Installing a wheel in Microsoft Fabric
Microsoft documents two approaches, and they suit different stages.
For shared, repeatable use: a Fabric Environment. Fabric supports custom library files in .whl, .py, .jar
and .tar.gz format. In the Environment’s Custom libraries page, upload the wheel, then Publish the
Environment and attach it to the notebooks (or set it as the workspace default). When you upload, you choose a publish
mode:
| Mode | What happens | Microsoft’s guidance |
|---|---|---|
| Full | Dependencies are resolved and a stable library snapshot is created at publish time. Publishing typically takes 3 to 6 minutes, and session start-up adds 1 to 3 minutes, depending on dependency size. | Recommended for production workloads, pipelines, and more than 10 packages |
| Quick | Publishing takes about 5 seconds; packages install when the notebook session starts | Notebooks only, not Spark job definitions |
For a quick, interactive test: inline install. %pip install in a notebook cell is session-scoped: it affects only
that session and isn’t part of the Environment. That’s fine while developing, and a poor fit for scheduled pipelines,
because every run pays the install time again.
%pip install /lakehouse/default/Files/wheels/javiperf-0.2.0-py3-none-any.whl
Two practical notes:
- Match the runtime. Fabric Runtime 2.0, the current generally available and default runtime, ships Apache Spark 4.1, Python 3.13 and Java 21. Test your wheel on those versions before attaching it. The Fabric Runtime comparison covers what changed from Runtime 1.3.
- Private networks block PyPI. With outbound access protection or a managed virtual network, public PyPI isn’t reachable. That’s one more reason to keep dependencies minimal and ship your own code as a wheel.
Inline installation has documented limits worth knowing before it reaches a scheduled run:
- Inline commands for Python libraries are disabled in notebook pipeline runs by default. Microsoft documents a
_inlineInstallationEnablednotebook activity parameter to enable them, and recommends an Environment instead. %pip installisn’t supported in high concurrency mode, nor in notebook reference runs.- It restarts the Python interpreter, so variables defined before it are lost. Put it at the top of the notebook.
- Use
%pip, not!pip: Microsoft notes that!pipinstalls a package only on the driver node.
A wheel in a notebook’s resources folder can be installed the same way, for a quick test:
%pip install "builtin/merchant_rules-1.0.0-py3-none-any.whl".
17. Versioning, testing and deployment
Once code is shared, every change is a change for all its callers. Handle it like any other production dependency.
- Semantic versioning. Bump the patch version for fixes, the minor version for compatible additions, and the major version for breaking changes. Before 1.0, say explicitly that minor versions may break the API.
- A changelog. Each release says what changed, especially behaviour changes. “Fixed null handling” is a behaviour change for anyone who relied on the old behaviour.
- Tests in CI. Unit tests on every commit, and a Spark integration test with a local session for anything that touches DataFrames. Make Spark tests fail, not skip, when Spark is unavailable in CI. A silently skipped test is worse than none.
- Pin in production. Pipelines should use an exact, tested version of the library, and upgrade deliberately: publish the new version to a test Environment, run the pipelines’ smoke tests, then promote.
- Deploy through your existing process. If notebooks are deployed with Git and deployment pipelines, the Environment and its libraries should follow the same path. See Microsoft Fabric CI/CD with fabric-cicd.
- Know what Git carries. When an Environment is committed, its public libraries become YAML and custom libraries are committed with their source files, up to 150 MB per commit. Notebook resources reach Git only if you enable it. Environment resources aren’t supported in Git or deployment pipelines, and custom pools aren’t supported in deployment pipelines.
- Source and testsUnit tests, local Spark tests in CI
- Build the wheelpython -m build; inspect its contents
- Version and changelogSemantic version, what changed
- Test EnvironmentUpload, publish, run pipeline smoke tests
- Production EnvironmentPromote the same file
- Notebooks attachPinned version, no inline installs
18. Security, compatibility, ownership and dependencies
A library runs inside every pipeline that installs it, so treat it as production code.
- Security. Keep secrets out of library code and out of its outputs. A shared logging helper that prints a connection string leaks it from every pipeline at once. Review what a library writes: logs, reports, error messages. JaviPerf, for example, records only exception types by default, because messages can contain data values.
- Supply chain. Know where every dependency comes from, and prefer fewer of them. Each transitive dependency is code you run without reviewing it.
- Compatibility. State the Python, Spark and Java versions you test, and test the ones your runtime uses. Behaviour
changes between versions are real: in our captured plans, a plain
@udfwas planned row-at-a-time (BatchEvalPython) on Spark 3.5.5 and 4.1.4, and Arrow-based (ArrowEvalPython) on PySpark 4.3.0 with default settings. - Ownership. Name an owner and a way to report problems. Decide how long old versions are supported.
- Licensing. Choose a license for anything shared beyond your team, and check your dependencies’ licenses. Both libraries in this article are Apache-2.0.
19. From repeated code to a package: a migration checklist
A step-by-step path from stage 1 to stage 3. You can stop at any step that’s good enough.
- Inventory the copies. Search the workspace for the logic’s distinctive lines and list every notebook that has a copy, with its owner and its consumers.
- Compare them. Decide which behaviour is intended. Turn deliberate differences into parameters; treat accidental ones as bugs and record them.
- Write characterization tests first. A small synthetic fixture with known expected output, run against the current behaviour, before you change anything.
- Separate logic from I/O. Functions take DataFrames and return DataFrames; paths, tables and credentials stay in the notebooks.
- Extract one module and make the tests pass with a local Spark session on your runtime’s Python and Spark versions.
- Choose a delivery route for now: a shared notebook with
%run, or an Environment.pyfile. - Replace the copies one notebook at a time. Run old and new side by side on the same input and compare row counts and rejected rows before you switch.
- When the logic is stable and shared beyond one team or workspace, add
pyproject.toml, a version, a changelog and a named owner. - Build the wheel in CI and inspect it: only your package, no tests or data, no pinned PySpark, no secrets.
- Publish it to a test Environment (Full mode for pipelines) and run each pipeline’s smoke test. Measure session start before and after.
- Promote the same file to production, attach the Environment, and remove the
%runcells, resource copies and inline installs it replaces. - Write down the upgrade policy: what counts as a breaking change, how long old versions are supported, and how consumers hear about releases.
20. Practical decision checklist
| Question | If yes | If no |
|---|---|---|
| Is the logic used by two or more pipelines? | Consider sharing it | Keep it in the notebook |
| Does a platform feature or maintained library already do it? | Use that, with a thin wrapper if needed | Continue |
| Is the logic yours (business rules, conventions, reviewed decisions)? | A good library candidate | Prefer an existing library |
| Has it been stable for a few weeks? | Package it | Start with a shared module |
| Is there a named owner? | Proceed | Don’t create the library yet |
| Can it be unit-tested without the pipeline? | Write the tests first | Separate the logic from the I/O |
| Does it stay off the per-row path? | Good | Rework the API to take whole collections or DataFrames |
| Is a performance claim part of the case for it? | Measure before and after: same output, repeated runs, explicit Spark actions | Don’t promise speed |
| Is it tested on your runtime’s Python and Spark versions? | Ship it to a test Environment | Test first |
A library is worth it when it turns a recurring decision into a tested, owned and versioned one. It isn’t worth it when it just moves code to a place where fewer people look.
Sources
- Python documentation: Modules,
time.perf_counter - Python Packaging User Guide: Packaging Python projects
- Apache Spark:
DataFrame.explain - Microsoft Learn: Fabric Runtime 2.0, Manage libraries in Fabric environments, Spark advisor, Spark monitoring overview, Spark application detail monitoring
- Microsoft Learn, reuse and orchestration: Notebook resources,
Develop, execute and manage notebooks (
%run), Notebook resources in VS Code (import builtin…), NotebookUtils: notebook run and orchestration, Library management, Environment resources, Notebook source control and deployment, Environment Git integration and deployment pipelines, High concurrency mode, Python notebooks - Apache Spark: ANSI compliance
Was this helpful?
What could be better?
Thanks — that helps me improve Javi Builds.
Continue learning
- Cheat sheetMicrosoft Fabric Workspace Settings Cheat SheetThe Microsoft Fabric workspace settings that change how a data engineering workspace behaves: Spark pools, environments and jobs, domain assignment, OneLake shortcut caching and diagnostics, and data workflow (Apache Airflow job) runtime pools, with what to verify for each.Open cheat sheet
- ArticleHow to Make Microsoft Fabric Notebooks FasterA practical workflow for reducing Fabric notebook startup, read, shuffle, transformation and Delta write time without guessing.Read article
- ArticlePython 3.15 Performance: What Actually Got Faster?See what actually got faster in Python 3.15, including JIT improvements, startup behavior, standard-library optimizations, profiling, and how to benchmark your own code.Read article
What should I build next?
I'm building Javi Builds around practical problems data engineers actually face. Tell me what you'd like to see next.
Stay in the loop
Get the Javi Builds updates you actually care about.
Check your inbox
I sent you a confirmation link. Your subscription will be active after you confirm it.