The Engine Under the Ecosystem. Pragmatic Rust for Python Developers. A flowing blue and yellow stream, in Python's colors, meets a dark grid of glowing orange circuit paths with a burst of sparks where the two collide.

Rust for Python Developers, a Visual Guide

TL;DR: Rust is already underneath a lot of the Python you run: ruff, uv, Pydantic, Polars and Granian. You don't need to write Rust to benefit, but knowing enough to read it pays off. The syntax looks like typed Python and cargo feels a lot like uv. What's genuinely new is the memory model Python hides from you, and the advice for using Rust from Python is to measure before you rewrite anything.

Rust has become the most influential way to make Python faster, and it's spreading well beyond Python, too. News broke recently that a major CPU maker is moving many of its device drivers to Rust. The trend has a running joke, too. Michael Kennedy, host of Talk Python, used to say that "if you switch to Rust, you're probably going to get VC funding," back when Astral and Pydantic took off. Christopher Trudeau, co-host of The Real Python Podcast, has the update: "Now it needs Rust plus AI, but I think that's still true."

So should a Python developer learn Rust? For most, the practical goal isn't becoming a Rust expert. It's knowing enough that poking around inside Pydantic, ty or some other extension makes sense, and maybe writing a little Rust to speed up a hot spot in your own code. Rust is a compiled, strictly typed language, so there is real new ground to cover, but a lot of it maps onto things Python developers already know. Talk Python's Up and Running with Rust course teaches it by comparison to Python for exactly that reason.

This guide takes the same route. It starts with where Rust already shows up in Python, then works through how the two languages differ: compiled code, the stack and the heap, hardware-sized integers, ownership and the borrow checker. After that come the tools (rustup, cargo and crates.io), the bridge back to Python through PyO3 and maturin, and when it's actually worth reaching for Rust at all.

Listen to the full episode

How fast is ruff? Linting all of CPython in 0.3 seconds

0.3 seconds, in giant glowing orange letters, for linting the entire CPython codebase from scratch. Below it: Ruff didn't skip anything. It's just written in Rust. Orders of magnitude change how you work.

Ruff is a linter and formatter for Python. A linter reads your code without running it and flags problems such as unused imports, likely bugs and style slips, and ruff can fix many of them for you. It's a command you run, not something you import:

ruff check .      # report problems in the current directory
ruff format .     # reformat the code

So why did Rust tooling take over so quickly? Most of the tools Python developers relied on for years were themselves written in Python, and they were slow. Mostly nobody minded. You started the job, went for another cup of coffee, and it was done when you got back.

The catch is that a little more speed changes nothing. A tool that's 10% faster goes unnoticed. A tool that's several zeros faster changes how you work. A couple of key libraries proved that early, and a whole wave of Rust-backed Python tools followed.

Ruff makes the point best. Michael Kennedy ran it over the Talk Python Training app, about 170,000 lines of Python, "not huge, but it's not a toy." It came back with four errors so fast he assumed it had skipped the subdirectories. It hadn't. It had parsed the whole app and checked it against around a hundred rules.

For a number anyone can compare against, linting the entire CPython code base from scratch takes 0.3 seconds, about three blinks of an eye. That's the figure in the image above. The 170,000 lines belong to the app, not to CPython.

Does it matter that ruff is written in Rust? For this kind of tool, not much. The Python grammar is public, and parser generators exist for many languages, so a fast linter could have been written in C or something else. Rust just happens to be where this kind of work is landing. That's also why this category is the easiest to forget about: you use ruff without ever seeing a line of Rust.

“Your world shifts when you start seeing, you know, orders of magnitude, right? Like 10% faster, you're not going to notice it when you're starting to talk multiple zeros times faster, this changes things.”

Christopher Trudeau

Three ways Rust shows up in Python: tools, libraries and servers

Rust is already in your stack. You just choose how to interact with it: as external tooling, optimized internal modules, or a host environment for your runtime. Model 1, Adjacent (Tools): Ruff, uv. Model 2, Internal (Libraries): Pydantic, Polars. Model 3, External (Servers): Granian.

Rust touches Python in three very different ways, and once you can tell them apart it's much easier to see what's going on in any given project.

Tools that happen to be Rust. Linters, formatters and package managers like ruff and uv are third-party programs you run to improve your Python. They never plug into the interpreter. They're written in Rust because Rust is fast (the previous section covers how much that matters), and they could just as easily have been written in another language.

Libraries Python imports. This is the most common mode, and where Rust is starting to shine. The library is written in Rust and compiled into a dynamic library on disk that Python loads as an ordinary module. Pydantic and Polars work this way. A thin veneer exposes the Rust code, and from Python it looks like any other import:

import polars as pl

df = pl.DataFrame({'lang': ['python', 'rust'], 'year': [1991, 2015]})
print(df['year'].mean())  # the crunching happens in Rust

That works because Python was designed from the start to integrate with lower-level languages. Big parts of the standard library are thin wrappers over the C standard library, and Rust can use the same interface C extensions use. Rust is a cleaner fit than C for this job: it has a learning curve, but it refuses to let you do a lot of dangerous things, and it brings iterators and collections along with the low-level control.

Rust programs that run Python. The third mode flips the relationship. A Rust program can embed the Python interpreter, using Python as a scripting or configuration language inside a larger system. Granian is a web server built in Rust that runs your Python web app inside it.

A food analogy helps keep these straight. Pydantic is a caramel-dipped apple, with Python outside and a Rusty core. Granian is a caramel M&M, a hard Rust shell around a Python center. The tools are apple slices next to a bowl of caramel: separate things you mix and match.

Why does this matter if you never plan to write Rust? Because the second and third modes are code you run every day. A lot of really important libraries are backed by Rust, so being able to read them, and maybe contribute, is worth something. The sections that follow are about getting there.

“So there's kind of three ways that Rust intersects with the Python world. And one has almost nothing to do with Python.”

Christopher Trudeau

Compiled vs interpreted: Rust machine code vs Python bytecode

The Physics of Two Languages. Python (The Stratosphere) vs Rust (The Engine Room). Execution: bytecode plus interpreter vs native machine code. Memory: garbage collected on the heap vs strict ownership and a stack/heap split. Sizing: boundless integers vs hardware-specific i8, i32, u8. Errors: discovered at runtime vs compile-time guarantees.

The table above is a decent map of where Python and Rust part ways. Three of its rows get their own sections later in this guide: memory in the stack and the heap and ownership, sizing in integer types, and errors in the borrow checker. This section takes the first row, since it's the one that trips people up most.

Wait, doesn't Python compile too? It does, and that's exactly where people get tangled up. Python compiles your source into bytecode, a binary representation that isn't specific to any platform. You can see it for yourself:

python -m py_compile hello.py   # writes the bytecode into __pycache__/
python -m dis hello.py          # prints it as readable instructions

Think of a formula in an Excel file. The file stores the formula in binary, but Excel is the thing that actually runs it. In the same way, the interpreter is specific to your machine and the bytecode is not. Hand someone your bytecode and, as long as they have a compatible Python version, their interpreter takes care of the rest.

Rust goes all the way down to machine code for one specific platform:

rustc hello.rs   # produces a native executable named hello
./hello

That's a real trade. Distribution gets way easier: here's the executable, go nuts, you're done (plus any dynamically loaded libraries it needs). But the binary only runs on the same kind of platform it was built for, so supporting several platforms means compiling for each of them. It's also why a Python package with Rust inside ships as a set of platform-specific wheels rather than a single source-only one.

That easy half is something Python developers envy. Michael Kennedy would love a python --build command that turns out one file to put on a server, hand to a person or drop into a Docker container, without a pile of supporting pieces around it.

The other casualty is the REPL, something Python developers take for granted. Rust has to compile, so a true REPL isn't really possible. There are hacks that fake one, and they're kind of hilarious: behind the scenes they keep a whole program around and recompile it every time you enter a line, wrapping each line in an invisible fn main and then running a cargo build and run. Even with Rust's compile speed that gets painful, and a scratch foo.rs file turns out to be the more practical habit.

“Just a thing that I could put on a server, I could give to a person, I could put in Docker, and it doesn't have to have a bunch of other stuff there to make it possible.”

Michael Kennedy

Stack vs heap: why everything in Python is a pointer

Hardware Alignment and The Heap. Python (The Stratosphere): a row of slots points to values scattered across memory, with a callout that everything is a pointer. Rust (The Engine Room): values sit side by side in the CPU cache. Python hides the hardware behind indirection. Rust forces you to map directly to it.

You can start writing Rust without fully understanding the stack and the heap, but you won't get very far. So here's the short version.

The stack is where function calls happen. When code jumps into a function, the address to come back to goes onto the stack, along with the function's parameters. Together they make a stack frame. When the function returns, its frame pops off, and the program carries on from the address that's now on top. The heap is the general space you allocate from. Longer-lived values, and things you pass around between functions, tend to be created there.

None of this is new with Rust. It's how compiled languages, and the machines under them, have always worked. Rust just puts more of it in front of you, and it's explicit about which values go where:

fn main() {
    // Four i32 values sit side by side on the stack.
    let nums = [10_i32, 20, 30, 40];
    let first = &nums[0] as *const i32 as usize;
    let second = &nums[1] as *const i32 as usize;
    println!("bytes between items: {}", second - first); // 4

    // Box::new puts its value on the heap.
    let boxed = Box::new(5_i32);
    println!("{}", *boxed + 1); // 6
}

In Python you only think about the stack when something fails and you get a stack trace. In Rust, once you start passing values around, two questions become very important: is this on the stack or the heap, and who owns it? The ownership section picks that up.

Here's the irony. Python never makes you think about pointers, while in C, C# and Rust you talk about stacks, heaps and dereferencing all the time. Yet Python is the most pointer-heavy of the lot, because literally everything lives on the heap. Even the number one is a pointer to an object on the heap. When everything is a pointer, there's nothing to tell apart, and that's how Python got away without exposing them.

CPython has an optimization that leans on this. It keeps one shared object for each of the small integers from -5 through 256, so every time you write a literal like 72, it points at the same immutable object instead of making a new one.

There's a performance angle, too. Where does a list of Python numbers land in memory? All over the heap. CPython's arenas and blocks try to keep things closer together, but the numbers are still out there somewhere. The four i32 values above are contiguous, four bytes apart, which is exactly what the CPU cache is built to work with.

“Well, this is how Python got away with not having pointers. It was everything's a pointer, so we don't have to differentiate.”

Christopher Trudeau

Integer types in Rust vs Python: i8, u8 and boundless ints

The Boundaries of the CPU. Python: a Boundless Integer; you are never going to get a Python integer into a CPU register, and limitless integers need hidden machinery to grow. Rust: crates labeled i8 (signed), u8 (unsigned 0-255) and f64. Rust removes the machinery and makes you choose your bit width up front.

Python's int has no upper limit. 2**100 is just a number, and so is one a thousand bytes long, which is why arbitrary-precision math is painless there. Rust goes the other way. Its integers are fixed-width and map straight onto what a CPU stores, so every integer type names its size and its sign: u8 is an unsigned 8-bit integer, i8 is a signed one, and each comes in 16, 32, 64 and 128-bit versions too. You pick one when you design the program. Usually that's no trouble. Every so often it puts you up against a boundary Python would never have shown you.

fn main() {
    println!("u8: {} to {}", u8::MIN, u8::MAX); // u8: 0 to 255
    println!("i8: {} to {}", i8::MIN, i8::MAX); // i8: -128 to 127

    let small: u8 = 250;
    println!("{:?}", small.checked_add(10)); // None
    println!("{}", small.wrapping_add(10));  // 4
}

Signed versus unsigned is a trade over the same bits. One byte holds 256 patterns. Read them as unsigned and you get 0 to 255. Read them as signed and the range is split across negative and positive numbers, so i8 runs from -128 to 127. You gain negatives and lose about half the top end.

What happens when a value doesn't fit depends on how it got there. A literal the type can't hold, like let x: u8 = 256;, is a compile error (literal out of range for u8). Arithmetic that overflows at runtime panics in a debug build with attempt to add with overflow, and in a release build it wraps around instead, so 255 plus 1 gives 0. The two methods in the code block above are how you ask for something else: checked_add hands back None, and wrapping_add wraps on purpose.

Python has signed and unsigned sizes too, just buried a layer down. Packing bytes into a network packet makes them matter a great deal. Doing math at a prompt, you never meet them. Rust, like most compiled languages, doesn't give you that choice.

What you get for the trouble is speed. Growing past the current chunk of memory takes machinery inside every Python integer, and that machinery is overhead on every number. A Python integer never lands in a CPU register. Rust has no such machinery, so its integers do exactly what the hardware does.

How jarring all this feels depends on where you start. After about 15 years of C++ and C#, Michael Kennedy's first reaction to Python's integers was that he must be doing something wrong, since there was nowhere to say how big the number was. Then it clicked: it just grows.

“So that beauty of Python's limitless integer means there has to be machinery inside of that to handle when you make it bigger than what the current chunk of memory is. And Rust doesn't have that machinery.”

Christopher Trudeau

Rust ownership explained for Python developers

Rule number 1: Only one thing can own a value. On the Python side, a runner hands copies of a baton to three others: pass a value, GC cleans up later. On the Rust side, one runner hands the single baton to the next: ownership transferred. Pass it around freely in Python and the garbage collector eventually cleans up. Pass it in Rust, and it won't compile.

Ownership is how Rust manages memory without a garbage collector. Python hides memory management so thoroughly that plenty of Python developers have never had to think about it. In Rust the rule is short: every value has exactly one owner, and when that owner goes away the value is freed. Passing a value into a function hands ownership to that function.

fn shout(s: String) {
    println!("{}!", s.to_uppercase());
}

fn main() {
    let name = String::from("Talk Python");
    shout(name);        // ownership of name moves into shout
    println!("{name}"); // error[E0382]: borrow of moved value: `name`
}

When shout returns, its s is dropped and the memory is released. The compiler knows that, so it refuses to let main touch name afterward. That check is what replaces the collector. Plain numbers are the exception: types like i32 are copied rather than moved, so passing one to a function doesn't use it up.

In Python you can pass a value to as many functions as you like and let the garbage collector sort out what's left. Carry that habit into Rust and it often turns into a compile error. Is that a feature or a nuisance? Both. It's the beauty of the language, because it makes sure certain kinds of bugs never happen. It's also a tax, because you can't play as loosely as you can in a dynamic language. You think you'll just pass this around, and then: wait, you can't.

For a newer developer that can be very frustrating. The threshold for getting started is higher, because you're constantly fighting the compiler before you get to try an idea. It's better to know that going in.

Ownership ties straight back to the stack and the heap. Once values pass between functions, where a value lives and who owns it decides when it's freed. Python hides all of that. Rust makes you answer for it at compile time, and then the compiler checks your answers.

The part of the compiler that enforces these rules is the borrow checker, and the next section covers what fighting it is actually like.

“There's a joke in the Rust world that there are no bugs. All your time isn't debugging. All your time is getting it to compile.”

Christopher Trudeau

The borrow checker and Rust's compiler error messages

The Trial of the Borrow Checker. An armored guard stands in front of a vault beside compiler output: error E0382, borrow of moved value name, with help: consider cloning the value. You will fight the compiler, but its error messages are explicitly helpful and correct 90% of the time. The reward: a whole category of memory bugs becomes impossible to write.

The borrow checker is the part of the Rust compiler that enforces ownership. You will spend time arguing with it, so it helps that the compiler is a good sparring partner. Its messages are very explicit, and they often include a suggestion along the lines of "maybe you need to do this." Here is what it prints for the moved String from the previous section (abridged):

error[E0382]: borrow of moved value: `name`
 --> own.rs:8:16
  |
6 |     let name = String::from("Talk Python");
  |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
7 |     shout(name);
  |           ---- value moved here
8 |     println!("{name}");
  |                ^^^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable

It points at the line where the value moved, the line where it was used afterward, and offers a fix. There are two. You can clone the value, which copies the data so both sides own one. Or you can lend it: pass a reference with &, a borrow, and the function looks at the value without taking it.

fn shout(s: &str) {
    println!("{}!", s.to_uppercase());
}

fn main() {
    let name = String::from("Talk Python");
    shout(&name); // lend it; main still owns name
    println!("{name}");
}

Borrows come with rules. You can have any number of shared references to a value or exactly one mutable reference, never both at once. Hold a reference to the first item of a Vec, then try to push onto it, and you get cannot borrow names as mutable because it is also borrowed as immutable. Growing the list could move its contents and leave that reference dangling, so the compiler stops you.

Once you know the vocabulary, an error stops being a mystery. It becomes a sign that the borrow checker is involved, and you go fix it. In Christopher Trudeau's experience the suggestions were right 80 or 90% of the time.

What do you get for the up-front work? Take C's way of storing text. "Talk Python" is those bytes followed by a null byte, and the null is the only way the program knows the string has ended. Write something longer than the space you set aside and there is no null, so reads keep walking into the next chunk of memory. Free a block but keep a pointer into it, and the computer will happily read whatever is there now. With two strings side by side you might just see a wrong message. With something trickier next door, the program falls over. These bugs only crash sometimes, which is what makes them nasty.

Rust isn't bug free. But safe Rust won't let you create that whole category. Types get the same treatment: without a type checker, a Python type mismatch shows up at runtime, and in Rust it's caught before the program exists. For anyone who learned C++ when a clean compile was only the start of the debugging, compiling means more in Rust than it used to in other languages.

“So Rust isn't bug free, but there is a category of bugs that it just doesn't let you create.”

Christopher Trudeau

Rust syntax for Python developers: fn, braces and implicit returns

If you read typed Python, you can read Rust. The same process_data function side by side in Python and Rust, with callouts for familiar types, identical returns and the same loops, and a warning on the Rust version's final false: implicit return, no keyword and no semicolon at the end of the block. Swap def for fn and embrace the brace brackets.

If you read typed Python, you can read Rust. Here is the same function in both. First Python:

def describe(name: str, scores: list[int]) -> bool:
    total = 0
    for s in scores:
        total += s
    if total > 100:
        print(name, 'high')
    elif total > 50:
        print(name, 'medium')
    return total > 100

Then Rust:

fn describe(name: &str, scores: &[u32]) -> bool {
    let mut total: u32 = 0;
    for s in scores {
        total += s;
    }
    if total > 100 {
        println!("{name} high");
    } else if total > 50 {
        println!("{name} medium");
    }
    total > 100
}

Most of it carries over. Loops work the same way, with the same for ... in. if and else are similar, though there is no elif: you write else if. There are tuples and arrays, iterators and collections. Type hints give you the biggest head start. Rust is strictly typed, so you say what everything is, and the declarations look like typed Python: a name, a colon and a type, plus an arrow for what a function returns. TypeScript and Swift have the same shape. The type goes after the name, where C would put it in front, which takes a little getting used to.

Then the differences show up. Some are cosmetic. Functions are declared with fn instead of def, which says exactly what the thing is. Blocks use braces instead of indentation, so whitespace doesn't matter to the parser.

Is that better? It's a trade. Indentation forces code whose structure matches how it reads. It also means copy and paste is problematic, and a reformat can quietly change what code does when one line is indented three spaces instead of four. Michael Kennedy has had exactly that happen. With braces, the formatting can be a total mess, even minified, and one reformat puts it back together reliably.

The difference with the biggest effect is that almost everything in Rust is an expression. A block in braces can produce a value, so you can assign the result of a whole block to a variable, a bit like an inline function:

let big = {
    let a = 60;
    let b = 50;
    a + b // no semicolon: this is the block's value
};

The same rule is behind the total > 100 at the end of describe. The last expression in a function, with no semicolon, is its return value, so you don't need a return keyword at the end of a function. Add a semicolon and the function returns (), and the compiler says mismatched types and suggests removing it. Expression-based blocks are elegant. Implicit returns are the part not everyone likes.

“I think after having coded in Python for almost two decades, I think I've come down on the side of screw the parser.”

Christopher Trudeau

Installing Rust: rustup, cargo and Cargo.toml for Python developers

Ecosystem Translation Matrix. pyenv maps to rustup (toolchain installer). uv and pip map to cargo (package and build manager). pyproject.toml maps to Cargo.toml (project manifest). PyPI and wheels map to crates.io and crates (package registry). The tooling maps perfectly. In fact, modern Python tools like uv were directly inspired by cargo.

Installing Rust takes two tools. rustup installs and updates the language itself, much like pyenv does for Python. It installs rustc, the compiler, and cargo, which is the tool you actually use, and it's very uv-like. You almost never call rustc yourself.

On Linux or macOS, you go to rust-lang.org, copy the shell command from the front page and paste it into a terminal. That means running a script from the internet on your machine, as plenty of installers ask you to. Here's the whole loop, from new project to release build:

cargo new hello          # Cargo.toml, src/main.rs, plus a git repo
cd hello
cargo run                # build and run the debug version
cargo run -q             # same, without cargo's build output
cargo build --release    # optimized build in target/release/

cargo new hello writes a Cargo.toml, the equivalent of pyproject.toml, a src directory and a stub main file with a working function in it, so the program compiles right away. At the time of recording, the manifest looks like this:

[package]
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]

By default cargo new also creates a git repository and a .gitignore. If you'd rather control that yourself, cargo new hello --vcs none skips it. cargo run builds and runs the program, so you don't have to dig the executable out of the target folder. Debug builds tend to be about 30% larger because they carry debug information, and the release build is the one you'd hand to someone. Cargo also prints two or three lines of build output before your program's own, which is what -q suppresses.

Rust moves fast. A new version ships every six weeks, which sounds insane coming from Python. How does anyone keep up? Editions are a separate idea, on a three-year cycle. Code stays compatible within an edition, and the compiler can build for older ones, so you set the edition target in Cargo.toml and old code keeps compiling. That's a forever promise of backward compatibility, and one view is that it "smells of maintenance hell", and that at some point the project may give up on it.

The influence between the two worlds runs in a circle. Much of Python's recent packaging revolution, uv included, was inspired by cargo, and cargo was designed when PyPI and npm already existed, so its designers could see what went wrong. Rust's target is also simpler: compiled code sheds a lot of the complications Python's dynamism creates, like a package that also needs a Fortran compiler. Wheels were a big step forward for Python, and the packaging story keeps making progress.

“The decision that the PSF made that managing packages wasn't really part of the language and that we should have this plethora of third-party tools to do that, I think that was a mistake. And I think the Rust people recognized that and decided to bundle this in.”

Christopher Trudeau

crates.io vs PyPI: Rust's small standard library and the trust problem

The Trust Trade-off. A Python toolbox overflowing under a Batteries Included banner, beside a small Rust toolbox with a warning sign amid floating crates. Rust keeps its standard library tiny; even a random number requires a third-party crate. You must manage your supply chain and decide whom to trust.

A package of Rust code is called a crate, the Rust equivalent of a wheel, and cargo installs and builds them the way uv does for Python. The registry is crates.io, Rust's answer to PyPI, and it has a fairly robust community writing and trading code. At the time of recording, it listed 331,019 crates against roughly 889,000 to 890,000 projects on PyPI.

The raw count isn't the core metric, though, and if anything it flatters Python. Python ships with batteries included. Rust deliberately keeps its standard library small to keep the footprint down, so there aren't many batteries. Even a random number comes from a crate. Here's what that looks like with the rand crate, checked against version 0.10.4:

cargo add rand
fn main() {
    let roll: u32 = rand::random_range(1..=6);
    println!("{roll}");
}

cargo add writes the dependency into Cargo.toml, the file that plays the role of pyproject.toml. In Python, the same job is a single import random with nothing to install and nothing new to trust.

The trade-off is about trust. Staying inside Python's standard library buys a degree of safety, and outside it you want someone who has used a package and vouches for it. For popular Python libraries there's enough written about them to get a feel. In Rust, the everyday basics live outside the standard library, so you make that trust call sooner and more often, and a newcomer may not yet know where the signal comes from. Some of that is probably just newness to the community. Still, given the state of supply chain attacks, the caution is fair.

Why is Python so different here? Mostly timing. It dates from around 1991, before PyPI, before the idea of a package manager, even before the web. Getting code after the fact was really hard, so a rich standard library made sense. If getting packages had been easier, the designers might have chosen differently. Rust arrived into a world where package managers already existed, and it could learn from them.

“If I'm in the Python world, I trust the standard library. If I stick to the standard library, I know I have a degree of safety.”

Christopher Trudeau

PyO3 and maturin: calling Rust from Python

The Bridge: PyO3 and Maturin. A Rust gear tagged with the pyfunction macro feeds through a funnel labeled Maturin and PyO3 into import my_rust_module. PyO3 maps the ABI, Maturin builds the wheel. Python was designed to integrate with lower-level C libraries. Rust simply uses the same door. To Python, your compiled Rust is just another module.

How does Rust code end up as something you can import? Python was designed from the get-go to integrate with lower-level languages. A good chunk of its standard library is a thin wrapper over the C standard library. The interface C extensions use works just as well for Rust, which is how Pydantic and Polars are built: the library is written in Rust, exposed through a very thin veneer, and Python treats it like any other module. Rust is often easier than C for this job, for the reasons covered in three ways Rust shows up in Python.

The most common way to build the bridge is a crate called PyO3. It defines the interface between your compiled dynamic library (a .so or .dll) and Python's ABI, and it works in two directions:

  • Python types in Rust. PyO3 has Rust objects that stand in for Python objects. PyInt, for example, gives your Rust code access to a Python integer.
  • Rust types for Python. It also maps ordinary Rust types for you, so a function that takes a 32-bit integer looks like it takes a normal integer from the Python side.

You choose what Python sees with macros, Rust's mechanism for changing how code gets compiled. Attach one to a regular Rust function or class, and it generates the mapping, including how the arguments line up. Here's a whole module, checked against PyO3 0.29.3 and maturin 1.16.0:

use pyo3::prelude::*;

#[pymodule]
mod fast_sum {
    use pyo3::prelude::*;

    /// Add up the squares of 1..=n.
    #[pyfunction]
    fn sum_of_squares(n: u64) -> u64 {
        (1..=n).map(|i| i * i).sum()
    }
}

Compile it and everything lands in a .so. Then maturin handles the packaging, which means installing the result into a virtual environment or building it into a wheel. A new project comes from maturin new -b pyo3 fast_sum, and from there:

uv venv
source .venv/bin/activate
uv pip install maturin
maturin develop
python -c "import fast_sum; print(fast_sum.sum_of_squares(10))"

That prints 385. maturin develop builds the crate and installs it into the active virtual environment, and maturin build --release produces a wheel for distribution. The u64 argument maps to a Python int: passing a string raises a TypeError, and passing -1 raises an OverflowError.

It doesn't have to be all or nothing: you can write most of a package in Python and only the hot part in Rust. For example, Polars ships as two wheels: a universal one that holds only Python code, and a platform-specific one with the compiled Rust library. Maturin will also bundle a mixed Rust and Python project for you (maturin new --mixed scaffolds one), in one wheel or several. It's no different from any other plugin mechanism. These are just the tools Rust gives you to build them.

“And from Python's perspective, once that's installed in the right place, you just import foo from bar as you would with any other module and you've got access to it all.”

Christopher Trudeau

When to rewrite Python in Rust: don't, then measure

The Golden Rule: Don't, then measure. A timeline chart where a tall Heroic Rust Rewrite spike saves only a tiny sliver of total time. Every call across the Python and Rust boundary has a cost, so chatty calls slow you down. Hand Rust big chunks of work, like Polars or Pydantic do, and take the answer back.

Once you know you can call Rust from Python, it's tempting to start rewriting the slow parts. There's probably plenty of low-hanging fruit: run a profiler and you may find that at least 20 lines of your code really matter.

Rust isn't free, though. Every call from Python into Rust crosses a boundary, and crossing it has a cost. If your code bounces back and forth constantly, or your objects keep crossing over, the overhead adds up. Writing it in Rust doesn't guarantee it'll be faster. It could make it slower. What works is the shape Polars and Pydantic use: hand Rust a big chunk of work, let it crunch, and take the answer back. With Polars that's heavy number crunching. With Pydantic the data arrives as JSON anyway and has to be transformed, so it makes sense to let that happen in Rust.

How do you know which part to hand over? The general advice on optimization is "don't and then measure." No matter how good you are at guessing up front, you eventually make the wrong assumptions. Build it, profile it, then find out where the time goes. Michael Kennedy has been wrong enough times about what was slow and what was fast that following his intuition would have meant months of bad choices.

Amdahl's Law explains why guessing is so expensive. It says that speeding up one part of a program is limited by how much of the total time that part takes. Say 20% of the time goes to one spot. Make that spot infinitely fast and the run time drops by about 20% at best. Now picture the heroic version: move that code from a single CPU thread to a GPU and make it a thousand times faster. If the whole thing takes five milliseconds, you've saved one. Hooray. And look how much harder your life just got, and how much more expensive the deployment is.

Measuring is getting easier, too. Python 3.15 adds a sampling profiler to the standard library. A sampling profiler periodically checks what the program is doing instead of instrumenting every call, and this one can attach to a process that's already running, such as one in production. The commands, checked against the built-in help of Python 3.15.2:

python -m profiling.sampling run script.py
python -m profiling.sampling attach -d 30 1234

run profiles a script from start to finish, and attach samples an existing process by its id (1234 here) for 30 seconds. Collect data on a live API for something like half a minute, step away, and see whether making one part faster would really be a big deal.

“As programmers, I think we often get tied up in the, oh, wouldn't it be cool if I made this code three times harder to read and it'll be, you know, half a millisecond faster. And how often do you call that? Once a year?”

Christopher Trudeau

awesome-python-rs: find a Rust-backed library before you write one

Don't Rewrite. Replace. A search bar for github.com/ritwiktiwari/awesome-python-rs links to orjson, cryptography and polars. Before you spend a weekend rewriting your slow JSON parser in Rust, check the awesome-list: someone has likely built a fast, drop-in, Rust-backed replacement already.

The Rust book teaches the language, but it can't show Rust at work in the Python world. awesome-python-rs can. It's a community-curated GitHub list, a massive one, of tools and libraries in the Python space that use Rust under the hood. If you'd rather read real code than textbook examples, it's a good place to start digging.

It also changes how you think about optimizing. The list includes drop-in replacements built for speed, among them a cryptography library and a JSON library, many of them faster alternatives to standard-library or pure-Python tools. Christopher's summary was that because they're written in Rust, they're "screamingly faster." So before rewriting a slow bit of your code in Rust, check whether someone has already shipped it as a library. Sometimes the fix is to swap your JSON parsing library and move on.

"Drop-in" needs a closer look. orjson, the JSON library linked below, covers the same ground as the standard library's json module, but its dumps returns bytes rather than a string. This was checked against orjson 3.13.0:

import json
import orjson

data = {'name': 'Talk Python', 'episode': 563}

json.dumps(data)    # '{"name": "Talk Python", "episode": 563}'
orjson.dumps(data)  # b'{"name":"Talk Python","episode":563}'

Swapping one in can mean a small edit where you call it, not a rewrite.

There's a trust angle too, and it ties back to the worries about crates. Many of these Python libraries are thin wrappers, sometimes just a few lines of API glue, around existing Rust libraries. Someone found a Rust library that does something useful, wished it were in Python, and exposed it as a module. That means you're not trusting a stranger who spent a weekend rewriting JSON parsing. You're leaning on a library the Rust community itself depends on (see the quote below).

Polars is the model case. It's a Rust library for Rust programmers, with a Python layer on top, so you get the Rust users and the Python users both exercising the same core.

“These are things with thousands of stars and many contributors because the Rust community themselves are using them, right?”

Christopher Trudeau

Is Rust hard to learn, and will it make you a better Python developer?

The Dual-Stack Mindset. Over a circuit board threaded with blue and orange light: fighting the borrow checker fundamentally changes how you think about software architecture. Learning Rust's strict memory rules makes you a highly deliberate, optimized Python developer, even if you never ship a compiled binary.

Rust has a reputation as a hard language. It's closer to the machine than Python, with less virtualization, and it expects a grounding in how that machine works. Writing C, device drivers or embedded systems builds that grounding. Christopher Trudeau, who started with C as a teenager, didn't find Rust hard, and he's careful to say that's about where he started, not about being smarter. For a developer who came up through PHP and Python, the same language is a whole other kind of experience.

So the friction is real, especially for newer developers, and the ownership section covers where most of it comes from. The friction also teaches something. The stack and the heap, who owns a value, how big a number is: Python handles all of it for you, and Rust puts it in front of you. Learning Rust is one way to find out what that handling involves, even if you never ship a compiled binary. Bob Belderbos of Pybites, who got into Rust recently after PHP and Python, thinks it's made him a better Python developer for exactly this reason, because he now thinks about memory more than a pure Python background would ask of him.

Ready to start? Begin at rust-lang.org. The documentation there is remarkably well written, and the Rust book is right on the site, easy to follow and full of really good examples. If you'd rather learn Rust by comparison to the Python you already know, Up and Running with Rust goes from zero through the stack, the heap and ownership to a compiled extension you import from Python with PyO3 and maturin. For the Python side of the memory story, Python Memory Management and Tips covers how CPython actually allocates and frees memory. And since Polars is the model Rust-backed library, Polars for Power Users shows what that Rust core buys you in practice.

“He actually thinks it's made him a better Python developer, because now he's thinking about memory and stuff like that a little more than you necessarily would if you've just come from Python.”

Christopher Trudeau

Talk Python's Mastodon Michael Kennedy's Mastodon