Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Rustdef Makes It Dead Simple to Call Rust in Python Notebook

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. rustimport is a Python library which allows you to import Rust source files directly from Python! It is similar to rustdef @ GitHub but targeting use cases in Python code instead of in Jupyter/Lab notebooks.

!pip3 install --user rustdef
import os

os.environ["PIP_USER"] = "yes"
os.environ["PIP_USER"]
'yes'
%load_ext rustdef
load rustdef
Loading...
     Created library package
    Updating crates.io index
      Adding pyo3 v0.15.1 to dependencies.
             Features:
             + extension-module
             + indoc
             + macros
             + paste
             + pyo3-macros
             + unindent
             - abi3
             - abi3-py310
             - abi3-py36
             - abi3-py37
             - abi3-py38
             - abi3-py39
             - anyhow
             - auto-initialize
             - eyre
             - hashbrown
             - indexmap
             - inventory
             - multiple-pymethods
             - nightly
             - num-bigint
             - num-complex
             - serde
%rustdef deps add itertools@0.10.5
    Updating crates.io index
      Adding itertools v0.10.5 to dependencies.
             Features:
             + use_alloc
             + use_std
%%rustdef --release
use itertools::Itertools;

#[pyfunction]
fn build_combs3() -> [usize; 230300] {
    let mut combs = [0; 230300];
    let mut i = 0;
    (3usize..50).for_each(|j| {
        (0..j).combinations(3).for_each(|comb| {
            combs[i] = (comb[2] << 8 | comb[1]) << 8 | comb[0];
            i += 1;
        });
    });
    combs
}

#[pyfunction]
fn build_combs3_index() -> [usize; 51] {
    let mut indexes = [0; 51];
    (3usize..50).for_each(|i| {
        indexes[i + 1] = indexes[i] + i * (i - 1) * (i - 2) / 6;
    });
    indexes
}
Use previous build
Defaulting to user installation because normal site-packages is not writeable
Processing /home/dclong/.rustdef/target/wheels/rustdef_cell_724f061b2fc00560a7a7b29e947ce6159286ce5e-0.1.0-cp310-cp310-linux_x86_64.whl
Installing collected packages: rustdef-cell-724f061b2fc00560a7a7b29e947ce6159286ce5e
Successfully installed rustdef-cell-724f061b2fc00560a7a7b29e947ce6159286ce5e-0.1.0
combs3 = build_combs3()
len(combs3)
230300
combs3[:5]
[131328, 131328, 196864, 197120, 197121]