Lecture 35 - Ship your code: modules, crates, and Python
Announcements
Learning objectives
By the end of today, I hope you will be able to (though this will not be assessed):
- Read the
mod,use, andpublines that have been at the top of your project files all term - Decide what should be
pub, and say what you're promising when you write it - Explain the difference between a package, a crate, and a module
- Say what changes when a program you run becomes a library somebody else calls
- Judge whether a piece of a Python program is worth moving to Rust, and how to hand it the data
Have you ever pip-installed Rust?
In the pre-work we asked about a Python package that turned out to be written in something else.
numpy,pandas: mostly C underneathpolars,pydantic,cryptography,tokenizers: Rust underneath
If you've typed import polars, you've run somebody else's Rust code!
Today we'll look at how they did that, and how you could too.
How does someone else get to your code?
Three sources:
- Another file in your project
- Another Rust project
- Another language
And it's the same task each time: draw a boundary, and mark what stays on one side or the other.
Let's imagine we want to share a sensor project
It has one file, src/main.rs.
It scores sensor readings: how far is each one from where it should be?
struct Reading {
id: u32,
value: f64,
baseline: f64,
}
fn load_readings(path: &str) -> Vec<Reading> { /* reads the CSV */ }
fn score_one(r: &Reading) -> f64 {
(r.value - r.baseline).abs().powf(1.5)
}
fn score_all(rs: &[Reading]) -> Vec<f64> {
rs.iter().map(score_one).collect()
}
fn mean(xs: &[f64]) -> f64 {
xs.iter().sum::<f64>() / xs.len() as f64
}
fn main() {
let rs = load_readings("sensors.csv");
println!("{}", mean(&score_all(&rs)));
}
Don't worry about the code details here - we'll cover reading them after break.
Boundary 1: another file in this project
Why split a program up at all?
Imagine Project 3 as one 900-line file. Two things can go wrong:
- It's hard to find things. The board, agents, minimax, and the tournament, all mixed up
- Everything can touch everything. Any function can call any other, so changing one can break all of them
mod addresses the first issue, and pub addresses the second.
mod makes a namespace
mod loading {
pub fn load(path: &str) -> Vec<Reading> { /* ... */ }
}
mod scoring {
pub fn score_all(rs: &[Reading]) -> Vec<f64> { /* ... */ }
}
fn main() {
let rs = loading::load("sensors.csv");
let scores = scoring::score_all(&rs);
}
A module is a named group of functions, types, and constants.
loading::load reads as "the load inside loading". Same :: as String::from.
Everything in a module starts private
mod scoring { fn adjust(x: f64) -> f64 { x.min(100.0) // cap a score at 100 } pub fn score(value: f64, baseline: f64) -> f64 { adjust((value - baseline).abs().powf(1.5)) } } fn main() { println!("{}", scoring::score(7.0, 3.0)); println!("{}", scoring::adjust(250.0)); }
You decide what to make pub
The compiler will let you write pub on everything. So the question is:
What do you want someone else to be able to reach?
Everything you mark pub is something you're promising to provide consistently and, preferably, forever.
Someone might come to depend on it, so you can't rename it or change what it returns without screwing with them.
Everything private, however, is yours to do with what you want.
Start private. Adding pub is easy, taking it away is hard.
pub works on everything
mod sensors {
pub struct Reading {
pub id: u32,
value: f64, // private field
baseline: f64, // private field
}
pub fn new(id: u32, value: f64, baseline: f64) -> Reading {
Reading { id, value, baseline }
}
}
A public struct can have private fields. Callers get a Reading and can't reach inside it, so the only way to make one is the function you gave them.
This shows up in Project 3's Board. Its cells are private, which is why you build one with Board::from_rows and change it with apply_move.
Paths say where to look
use crate::board::{Board, Cell, Position};
"Start at the top of this crate, go into board, and bring me these three names."
use super::*;
"Start at the module above this one, and bring me everything." It's the first line of every mod tests, and super is like cd ...
Moving modules into files
Once a module is big, we give it its own file.
src/
main.rs
loading.rs
scoring.rs
src/main.rs:
mod loading; // "go find src/loading.rs"
mod scoring;
fn main() {
let rs = loading::load("sensors.csv");
println!("{}", scoring::mean(&scoring::score_all(&rs)));
}
src/scoring.rs:
use crate::loading::Reading;
pub fn score_all(rs: &[Reading]) -> Vec<f64> { /* ... */ }
pub fn mean(xs: &[f64]) -> f64 { /* ... */ }
There's no mod scoring { } wrapper inside the file. The file is the module.
You've seen lines like this in your projects
The top of Project 3's minimax.rs:
use crate::agent::Agent;
use crate::board::{Board, Cell, Position};
use crate::player::Player;
And the start of its lib.rs:
pub mod agent;
pub mod board;
pub mod game;
This is what lets me define something in one file and use it in another.
Boundary 2: another Rust project
Package, crate, module
- Package: your project folder, the thing with a
Cargo.toml. Roughly, your repo - Crate: one thing that gets compiled. Roughly, your program or your library
- Module: a namespace inside a crate. Roughly, a file

Most of the time: one package, one crate, several modules.
Two kinds of crate
Binary crate. Has main(). Compiles to something you run.
sensor_tool/
Cargo.toml
src/main.rs
cargo new sensor_tool
Library crate. No main(). Compiles to something other code calls.
sensor_scoring/
Cargo.toml
src/lib.rs
cargo new --lib sensor_scoring
Every crate you've added to a Cargo.toml is the second kind.
Project 3 is one package with three crates
tictactoe/
Cargo.toml the package
src/
lib.rs library crate: the board, the agents, minimax
main.rs binary crate: cargo run
bin/arena.rs binary crate: cargo run --bin arena
Inside the library, minimax.rs says:
use crate::board::Board;
And main.rs says:
use tictactoe::board::Board;
rand, from the other side
Project 1 came with this already in it, in Cargo.toml and the random strategy:
[dependencies]
rand = "0.10"
use rand::random_range;
let guess = random_range(min..max);
Somebody wrote that lib.rs. They decided random_range was public and a lot of other things weren't. Those private things they can change without affecting anyone who uses the package.
Turning our program into a library
src/lib.rs replaces src/main.rs, and the top of the crate is now the public interface.
// src/lib.rs
mod loading;
pub mod scoring;
pub use scoring::{mean, score_all};
Two things changed, and both are small:
main()is gone. There's nothing to runpubnow decides what the outside world can reach (as opposed to whatmain.rscan use)
loading is still private.
The docs page is your pub list
cargo doc --open
That builds a website from your crate: every pub item, with its /// comments. (Try it on your project!)
docs.rs is that same page for every crate on crates.io. Here's rand's.
Installing and using public crates
Finding one: crates.io, the registry.
Adding one:
cargo add rand
which writes this into Cargo.toml for you:
[dependencies]
rand = "0.10"
Version numbers are MAJOR.MINOR.PATCH. "0.10" means "0.10.anything", so you get bug fixes without surprises. Cargo.lock records exactly what you built with.
Crates worth using
We've used: rand, clap (command-line arguments), plotters, regex
Data work: csv, serde (JSON and friends), ndarray (NumPy-shaped arrays), polars (DataFrames)
General: chrono (dates), rayon (parallelism, coming the week after break)
Before you add one, look at three things on crates.io: recent downloads, when it was last updated, and whether the docs exist.
Boundary 3: another language
Now your teammates write Python
Your team has a Python pipeline. Pandas, scikit-learn, matplotlib, everything built out.
But... one loop in it takes four minutes.
Nobody's going to rewrite that pipeline in Rust (right?)
You just want to replace the loop and leave everything else alone.
PyO3
A crate that lets Rust build something Python can import.
// src/lib.rs
use pyo3::prelude::*;
#[pymodule]
mod sensor_scoring {
use pyo3::prelude::*;
#[pyfunction]
fn score_all(values: Vec<f64>, baselines: Vec<f64>) -> Vec<f64> {
values
.iter()
.zip(baselines.iter())
.map(|(v, b)| (v - b).abs().powf(1.5))
.collect()
}
}
Look at what that is: a library crate, a mod, and two decorators.
The function inside is ordinary Rust.
#[pyfunction] acts like pub for a different audience.
Building it: maturin
pip install maturin
maturin new --bindings pyo3 sensor_scoring
You get both config files, because it's both kinds of project at once:
sensor_scoring/
Cargo.toml the Rust side
pyproject.toml the Python side
src/lib.rs your code
Write your Rust, then:
maturin develop --release
That compiles the crate and installs it into your active Python environment, the same place pip install puts things.
Same --release as cargo run --release, and it matters just as much. Without it, this module is slower than the Python it replaces.
And then it's just Python
import pandas as pd
import matplotlib.pyplot as plt
import sensor_scoring
df = pd.read_csv("sensors.csv")
scores = sensor_scoring.score_all(
df["value"].tolist(),
df["baseline"].tolist(),
)
plt.hist(scores, bins=50)
plt.show()
Loading and plotting in Python, the slow part in Rust.
Build it, import it
maturin develop --release
python
>>> import sensor_scoring
>>> sensor_scoring.score_all([7.0, 5.0], [3.0, 9.0])
[8.0, 8.0]
We ran both
A million readings, on my laptop:
| Time | |
|---|---|
| Plain Python loop | ~100 ms |
Design A: score_one, a million calls | ~115 ms |
Design B: score_all, one call | ~28 ms |
Design A moved the arithmetic into Rust and got slower.
The lesson: cross over rarely, and carry a lot with you when you do
Before you reach for Rust
NumPy does this scoring in about 8 ms:
scores = np.abs(values - baselines) ** 1.5
NumPy is the same trick, already done for you: one call, the whole column, a compiled loop underneath.
Reach for Rust when the loop can't be written as whole-column operations: each row depends on the one before it, there's real branching, or you're walking a tree.
Appendix: modules inside modules
mod pipeline { pub mod cleaning { pub fn remove_nulls() { println!("cleaned"); } } mod analysis { pub fn compute_mean() { println!("mean"); } } } fn main() { pipeline::cleaning::remove_nulls(); pipeline::analysis::compute_mean(); }
compute_mean is pub, and main still can't reach it: error[E0603]: module analysis is private. Every module on the way down has to be pub too.
An unlocked room inside a locked building is still unreachable.
Appendix: why a test can call a private function
fn half(n: i32) -> i32 { // private
n / 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_half() {
assert_eq!(half(10), 5);
}
}
mod tests is a module like any other, nested inside the file.
super is the file around it, and * is everything in there. A module can see its parent's private things, so a test can call a private helper.