Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rust-python-example

> 包管理
Open source

Example of using Rust to Extend Python

789 stars0 likes1 views
WebsiteGitHub

About

Example of using Rust to Extend Python

Speed up your Python using Rust

What is Rust?

Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.

Featuring

  • zero-cost abstractions
  • move semantics
  • guaranteed memory safety
  • threads without data races
  • trait-based generics
  • pattern matching
  • type inference
  • minimal runtime
  • efficient C bindings

Taken from: from rust-lang.org

Why does it matter for a Python developer?

The better description of Rust I heard from Elias a member and the Rust Guru of the Rust Brazil Telegram Group

Rust is a language that allows you to build high level abstractions, but without giving up low level control - that is, control of how data is represented in memory, control of which threading model you want to use etc.
Rust is a language that can usually detect, during compilation, the worst parallelism and memory management errors (such as accessing data on different threads without synchronization, or using data after they have been deallocated), but gives you a hatch escape in the case you really know what you're doing.
Rust is a language that, because it has no runtime, can be used to integrate with any runtime; you can write a native extension in Rust that is called by a program node.js, or by a python program, or by a program in ruby, lua etc. and, on the other hand, you can script a program in Rust using these languages. -- "Elias Gabriel Amaral da Silva"

There are a bunch of Rust packages out there to help you extending Python with Rust.

I can mention Milksnake created by Armin Ronacher (the creator of Flask) and also PyO3 The Rust bindings for Python interpreter

See a complete reference list at the bottom.

For this post, I am going to use Rust Cpython, it's the only one I have tested, it is compatible with stable version of Rust and found it straightforward to use.

NOTE: PyO3 is a fork of rust-cpython, comes with many improvements, but works only with the nightly version of Rust, so I prefered to use the stable for this post, anyway the examples here must work also with PyO3.

Pros: It is really easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance.

Cons: The distribution of your project/lib/framework will demand the Rust module to be compiled on the target system because of variation of environment and architecture, there will be a compiling stage which you don't have when installing Pure Python libraries, you can make it easier using rust-setuptools or using the MilkSnake to embed binary data in Python Wheels.

Python is sometimes slow

Yes, Python is known for being "slow" in some cases and the good news is that this doesn't really matter depending on your project goals and priorities. For most projects this detail will not be very important.

However, you may face the rare case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing.

Example

Lets say you have a Python function which does some kind of string processing, take the following easy example of counting pairs of repeated chars but have in mind that this example can be reproduced with other string processing functions or any other generally slow process in Python.

bash
# How many subsequent-repeated group of chars are in the given string? 
abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here}
  1   2    3        4    5   6 

Python is pretty slow for doing large string processing so you can use pytest-benchmark to compare a Pure Python (with Iterator Zipping) function versus a Regexp implementation.

bash
# Using a Python3.6 environment
$ pip3 install pytest pytest-benchmark

Then write a new Python program called doubles.py

…

Run pytest to compare:

…

Lets take the Mean for comparison:

  • Regexp - 27.0167 ** crate is how we call Rust Packages.

Having rust installed (recommended way is https://www.rustup.rs/) Rust is also available on Fedora and RHEL rust-toolset

I used rustc 1.21.0

In the same folder run:

bash
cargo new pyext-myrustlib

It creates a new Rust project in that same folder called pyext-myrustlib containing the Cargo.toml (cargo is the Rust package manager) and also a src/lib.rs (where we write our library implementation)

Edit Cargo.toml

It will use the rust-cpython crate as dependency and tell cargo to generate a dylib to be imported from Python

toml
[package]
name = "pyext-myrustlib"
version = "0.1.0"
authors = ["Bruno Rocha "]

[lib]
name = "myrustlib"
crate-type = ["dylib"]

[dependencies.cpython]
version = "0.1"
features = ["extension-module"]

Edit src/lib.rs

What we need to do:

  1. Import all macros from cpython crate

  2. Take Python and PyResult types from cpython in to our lib scope

  3. Write the count_doubles function implementation in Rust, note that this is very similar to the Pure Python version except for:

    • It takes a Python as first argument, which is a reference to the Python Interpreter and allows Rust to use the Python GIL
    • Receives a &str typed val as reference
    • Returns a PyResult which is a type that allows the raise of Python exceptions
    • Returns a PyResult object in Ok(total) (Result is a enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a PyResult the compiler will take care of wrapping our Ok on that type. (note that our PyResult expects a u64 as return value)
  4. Using py_module_initializer! macro we register new attributes to the lib, including the __doc__ and also we add the count_doubles attribute referencing our Rust implementation of the function

    • Attention to the names libmyrustlib, initlibmyrustlib and PyInit_myrustlib which is suffixed by our library name (defined in Cargo.toml)
    • We also use the try! macro which is the equivalent to Python's try.. except
    • Return Ok(()) - The () is an empty result tuple, the equivalent of None in Python
rust
#[macro_use]
extern crate cpython;

use cpython::{Python, PyResult};

fn count_doubles(_py: Python, val: &str) -> PyResult {
    let mut total = 0u64;

    for (c1, c2) in val.chars().zip(val.chars().skip(1)) {
        if c1 == c2 {
            total += 1;
        }
    }

    Ok(total)
}

py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | {
    try!(m.add(py, "__doc__", "This module is implemented in Rust"));
    try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str))));
    Ok(())
});

Now lets build it in cargo

bash
$ cargo build --release
    Finished release [optimized] target(s) in 0.0 secs

$ ls -la target/release/libmyrustlib*
target/release/libmyrustlib.d
target/release/libmyrustlib.so*   NOTE: on **Fedora** you must get a `.so` in other system you may get a `.dylib` and you can rename it changing extension to `.so`

```bash
$ cd ..
$ ls
doubles.py pyext-myrustlib/

$ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so

$ ls
doubles.py myrustlib.so pyext-myrustlib/

Having the myrustlib.so in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module.

Importing from Python and comparing the results

Edit your doubles.py now importing our Rust implemented version and also adding a benchmark for it.

python
import re
import string
import random
import myrustlib   #   Interesting that **Regex** version is only 2x faster than Pure Python :)

> NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different.

# Updates and improvements

After this article has been published I got some comments on [r/python](https://www.reddit.com/r/Python/comments/7dct9v/use_rust_to_write_python_modules/)
and also on [r/rust](https://www.reddit.com/r/rust/comments/7dctmp/red_hat_developers_blog_speed_up_your_python/) 

The contributions come as [Pull Requests](https://github.com/rochacbruno/rust-python-example/pulls?utf8=%E2%9C%93&q=is%3Apr) and you can send a new if you think the functions can be improved.

Thanks to: [Josh Stone](https://github.com/cuviper) we got a better implementarion for Rust which iterates the string only once and also the Python equivalent.

Thanks to: [Purple Pixie](https://github.com/purple-pixie) we got a Python implementation using `itertools`, however this version is not performing any better, needs improvements.

## Iterating only once

```rust
fn count_doubles_once(_py: Python, val: &str) -> PyResult {
    let mut total = 0u64;

    let mut chars = val.chars();
    if let Some(mut c1) = chars.next() {
        for c2 in chars {
            if c1 == c2 {
                total += 1;
            }
            c1 = c2;
        }
    }

    Ok(total)
}
python
def count_doubles_once(val):
    total = 0
    chars = iter(val)
    c1 = next(chars)
    for c2 in chars:
        if c1 == c2:
            total += 1
        c1 = c2
    return total

Python with Itertools

python
import itertools

def count_doubles_itertools(val):
    c1s, c2s = itertools.tee(val)
    next(c2s, None)
    total = 0
    for c1, c2 in zip(c1s, c2s):
        if c1 == c2:
            total += 1
    return total

Why not C/C++/Nim/Go/Ĺua/PyPy/{other language}?

Ok, that is not the purpose of this post, this post was never about comparing Rust X other language, this post was specifically about how to use Rust to extend and speed up Python and by doing that it means you have a good reason to choose Rust instead of other language or by its ecosystem or by its safety and tooling or just to follow the hype, or simply because you like Rust doesn't matter the reason, this post is here to show how to use it with Python.

I (personally) may say that Rust is more future proof as it is new and there are lots of improvements to come, also because of its ecosystem, tooling and community and also because I feel comfortable with Rust syntax, I really like it!

So, as expected people started complaining about the use of other languages and it becomes a sort of benchmark, and I think it is cool!

So as part of my request for improvements some people on Hacker News also sent ideas, martinxyz sent an implementaion using C and SWIG that performed very well.

C Code (swig boilerplate ommited)

c
uint64_t count_byte_doubles(char * str) {
  uint64_t count = 0;
  while (str[0] && str[1]) {
    if (str[0] == str[1]) count++;
    str++;
  }
  return count;
}

And our fellow Red Hatter Josh Stone improved the Rust implementation again by replacing chars with bytes so it is a fair competition with C as C is comparing bytes instead of unicode chars.

rust
fn count_doubles_once_bytes(_py: Python, val: &str) -> PyResult {
    let mut total = 0u64;

    let mut chars = val.bytes();
    if let Some(mut c1) = chars.next() {
        for c2 in chars {
            if c1 == c2 {
                total += 1;
            }
            c1 = c2;
        }
    }

    Ok(total)
}

There are also ideas to compare Python list comprehension and numpy so I included here

Numpy:

python
import numpy as np

def count_double_numpy(val):

Issues· 7 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonccargocfficomparison

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category包管理
PricingOpen source

> Related tools

N
npm
Node.js 默认包管理器
P
pnpm
高效节省磁盘的 Node 包管理器
I
is-gif
Check if a Buffer/Uint8Array is a GIF image